0
$summary=$query->result_array();    //where the original array is created 
print_r($summary);                     //dump contents

Produces this:

Array ( [0] => Array ( [RecordID] => 2 [UserID] => 3 [BookID] => 1 [Title] => FirstBook ) [1] => Array ( [RecordID] => 3 [UserID] => 3 [BookID] => 2 [Title] => Sequel ) )

I would now like to pad the multi dimensional array with a price element so as to create the results of

Array ( [0] => Array ( [RecordID] => 2 [UserID] => 3 [BookID] => 1 [Title] => FirstBook [Price] => 99 ) [1] => Array ( [RecordID] => 3 [UserID] => 3 [BookID] => 2 [Title] => Sequel  [Price] => 99) )

The only way I can think of doing this is to break the multidimensional array into one-dimensional arrays, modify them, and then re-assemble them. Doesn't sound terribly efficient though. Any suggestions?

3 Answers 3

1

You can update the internal arrays by reference, note the & here:

foreach($summary as &$details){
    $details['Price'] = $price;  // wherever $price comes from...
}
Sign up to request clarification or add additional context in comments.

2 Comments

Quick question: What is the technical name of that ampersand that you highlighted? "note the & here". It's not an operator is it? I'm trying to read up about it in PHP documentation.
@Maxcot read assigment and references
0

try to use:

foreach ($summary as $idx => &$arrValue)
    $arrValue['Price'] = ###;

Comments

0

If you're fixed on your dimensions, iterate with a reference and modify $summary in place...

<?php
foreach ($summary as &item) {
   $item['price'] = 99;
}

If you have particular objections/issues with references:

<?php
foreach ($summary as $key=>item) {
   $summary[$key]['price'] = 99;
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.