Add element to PHP associative array in loop - php

I've looked but can't find an answer for my specific use case. I want to add an element to a multidimensional array while looping through it. What I have before the loop:
Array
(
[fname] => Monty
[lname] => Python
[phone] => 555 555 1212
[email] => a#b.com
[modelList] => Array
(
[0] => Array
(
[id] => 1
[modelName] => X-Wing
[remarks] =>
[htmlRemarks] =>
[category] => Vehicles
[catID] => 178
[attachedToBase] => 1
[oversized] => 0
)
)
)
In code, I'm looping through the [modelList] array and after doing some database operations what I want to do is append new elements to each model array - in the case below, the [dbID]:
Array
(
[fname] => Monty
[lname] => Python
[phone] => 555 555 1212
[email] => a#b.com
[modelList] => Array
(
[0] => Array
(
[id] => 1
[modelName] => X-Wing
[remarks] =>
[htmlRemarks] =>
[category] => Vehicles
[catID] => 178
[attachedToBase] => 1
[oversized] => 0
[dbID] => 907
)
)
)
All inputs are from a form POST, and in my php handler:
// Loop thru model entries
$modelList = json_decode($_POST["modelList"], TRUE);
foreach($modelList as $model) {
(do some work)
// Add the new element
array_push($model['dbID'], $newID);
}
But this throws an error:
PHP Warning: array_push() expects parameter 1 to be array, null given
How can I add the new element to the sub-array?

array_push
Push one or more elements onto the end of array
You can't add a key value item to an array using array_push.
Use this instead :
foreach ($modelList as $key => $model){
$modelList[$key]['dbID'] = $newID;
}

Based on your snippet with the loop are you trying to actually update the dbID?
If so, you should change the logic to:
foreach ($modelList as $key => $model) {
(do some work)
$modelList[$key]['dbID'] = $newID;
}
Why:
you cannot change contents of the array you are looping over (unless accessed by reference)
in your example code $model['dbID'] is number 907 which is not an array, hence the error message

Found it - I needed to use a reference to $model in order to update it
// Loop thru model entries
$modelList = json_decode($_POST["modelList"], TRUE);
foreach($modelList as &$model) {
(do some work)
// Add the new element
$model['dbID'] = $newID;
}
unset($model);

Related

Adding to a multidimensional associative array (in PHP)

I'm returning an associative array via PDO that has the structure:
Array
(
[0] => Array
(
[pesttopicID] => 42
[sPestName] => CMSM Trap Surveying and Pest Management
[quizID] => 609
[bTier1] => 1
[sDesc] => Workshop assessment
)
[1] => Array
(
[pesttopicID] => 34
[sPestName] => Trap Surveyor
[quizID] => 451
[bTier1] => 1
[sDesc] => Competency for CM OAP
)
)
I want to add a key-value pair to the "inner" array, but all my attempts of trying to use posted solutions to the generic issue of adding to an associative array...
:
$results = $statement->fetchAll(PDO::FETCH_ASSOC);
$newkey='myNewKey';
$newval='myNewValue';
foreach($results as $row){
$results[][$newkey] = $newval;
foreach ($row as $key=>$value){
... some reporting stuff
}
}
...result in the pair being added to the "outer" array e.g.
Array
(
[0] => Array <---- I want the new pair in this "inner" array
(
[pesttopicID] => 42
[sPestName] => CMSM Trap Surveying and Pest Management
[quizID] => 609
[bTier1] => 1
[sDesc] => Workshop assessment
)
[1] => Array <---- I want the new pair in this "inner" array
(
[pesttopicID] => 34
[sPestName] => Trap Surveyor
[quizID] => 451
[bTier1] => 1
[sDesc] => Competency for CM OAP
)
[2] => Array
(
[myNewKey] => myNewValue
)
)
Is this possible?
Thanks/Tom
You have to it like below:-
$newkey='myNewKey';
$newval='myNewValue';
foreach($results as &$row){ //use reference variable
$row[$newkey] = $newval;// remove the second foreach if not necessary
//if second foreach is necessary then add it no problem
}
Output:-https://eval.in/856983
Or you can do like this also:-
$newkey='myNewKey';
$newval='myNewValue';
foreach($results as $key=>$row){ //use key now
$results[$key][$newkey] = $newval;// remove the second foreach if not necessary
//if second foreach is necessary then add it no problem
}
Output:-https://eval.in/856987

Replace the array values with html image tag in php

I have here an array below:
<?php
print_r( $result );
?>
If I am going to execute the code above, it resulted below:
Array
(
[0] => Array
(
[id] => 1
[uploaded_by] => 1
[image_url] => http://localhost/dir/img_2.jpg
[work_description] => test
[date_added] => 2017-08-03 02:12:38
)
[1] => Array
(
[id] => 2
[uploaded_by] => 1
[image_url] => http://localhost/dir/img_4.jpg
[work_description] => test
[date_added] => 2017-08-03 02:13:04
)
[2] => Array
(
[id] => 3
[uploaded_by] => 1
[image_url] => http://localhost/dir/img_2.jpg
[work_description] => test
[date_added] => 2017-08-03 02:46:28
)
[3] => Array
(
[id] => 4
[uploaded_by] => 1
[image_url] => http://localhost/dir/img_2.jpg
[work_description] => sdfsdf
[date_added] => 2017-08-03 02:46:34
)
)
Now, from the $result array I wanted to change the values of all image_url
programmatically using php into an image in html.
example:
http://localhost/dir/img_2.jpg will become
<img src="http://localhost/dir/img_2.jpg"/>
Those values must be changed if I am going to execute the code.
Does anybody know?
You can put it in a foreach and modify only the part what you want:
foreach($result as $key => $value) {
$result[$key]['image_url'] = '<img src="'.$value['image_url'].'"/>';
}
print_r($result);
You can use a compact syntax and modify the subarray elements by reference:
Code: (Demo)
foreach ($result as &$subarray) { // & means modify by reference, so you are overwriting the input array, not traversing a copy.
$subarray['image_url'] = "<img src=\"{$subarray['image_url']}\"/>";
}
var_export($result);
There is no need to declare $key because the foreach is traversing the actual input array, not a copy of the input array. The image_urls are simply overwritten with each iteration.

PHP array not setting custom key in a foreach loop

I'm looping through a database object returned by MySQL in CodeIgniter 2.x (PHP). The array $gifts has been declared outside the loop before it begins.
There is an inner loop and an outer loop. The outer loop generates the second array example below. The inner loop generates the problem array.
In LINE 2, $i['gifts'][$row->id_gift] correctly setting the keys with the desired id $row->id_gift. In LINE 1, it is not. The array key is being assigned numerically in order from 0-n as if it were being set with $gifts[][$sd] = $row->$sd.
Any thoughts on why?
$query = $this->db->get();
if ($query->num_rows() > 0)
{
foreach ($query->result() as $row)
{
foreach ($select_details as $sd)
{
$gifts[$row->id_gift][$sd] = $row->$sd; // LINE 1
$i['gifts'][$row->id_gift] = array('merchant_rank'=>$i['merchant_rank'],'rank'=>$row->rank); // LINE 2
}
}
}
$select_details = array('id_gift','id_group','rank');
Array (LINE 1) output sample:
Array (
[0] =>
Array (
[id_gift] => 392
[id_group] => 244
[rank] => 1
)
[1] => Array (
[id_gift] => 287
[id_group] => 239
[rank] => 1
)
[2] => Array (
[id_gift] => 264
[id_group] => 4
[rank] => 1)
)
Array (LINE 2) output sample (note the correct keys in the gifts array):
Array (
[0] => Array
(
[id] => 49
[id_group] => 49
[id_merchants] => 116
[gifts] => Array
(
[392] => Array
(
[merchant_rank] => 1
[rank] => 1
)
[287] => Array
(
[merchant_rank] => 1
[rank] => 2
)
[264] => Array
(
[merchant_rank] => 1
[rank] => 3
)
)
)
)
RESOLVED. See my answer below if you're curious. Thanks for your help #Spartan and #DontPanic.
Okay, I figured out the problem. And the more experienced programmers among you might not be all that surprised.
Later in the script I'm using a multidimensional array sort that's destroying the keys. I'm sure there's a way to prevent that, but that's not pertinent here.
usort($gifts, function($a, $b) {
return $a['rank'] - $b['rank'];
});

JSON PHP Decode

i have an extern JSON File and no problems to get Airline, Price, etc..
But how can i get [ACE] ?
[success] => 1
[data] => Array
(
[ACE] => Array
(
[0] => Array
(
[price] => 477
[airline] => AB
[flight_number] => 2434
[departure_at] => 2014-08-09T12:30:00Z
[return_at] => 2014-08-24T08:35:00Z
[expires_at] => 2014-04-03T22:46:17Z
)
)
$foo = $json['data']['ACE']; should do it.
Unless you want to get the key from the $data array, in which case:
foreach ($json['data'] as $k=>$v) {
$foo = $k; // this is 'ACE'.
break;
}
Edited as per comment.
['ACE'] is an array?
Your getting the data from it starting with the first - [0]
Then the ['price'] of the first one?

php array merge with value of parent array

I need to merge an array with value of parent array.
$testArr=unserialize('a:6:{s:5:"queue";a:2:{i:6;s:1:"5";i:5;s:1:"2";}s:3:"sum";a:2:{i:6;s:3:"765";i:5;s:3:"2.1";}s:7:"sumAccD";a:2:{i:6;s:3:"543";i:5;s:3:"3.1";}s:7:"sumAccC";a:2:{i:6;s:2:"54";i:5;s:3:"3.3";}s:7:"comment";a:2:{i:6;s:12:"test comment";i:5;s:6:"111222";}s:3:"yt0";s:0:"";}');
$ret = array();
foreach ($testArr as $pkey => $pval) {
if (is_array($pval)) {
foreach ($pval as $pvkey => $pvval) {
$ret[$pvkey] = array($pkey => $pvval);
}
}
}
echo '<pre>', print_r($ret), '</pre>';
In this case it prints out
Array
(
[6] => Array
(
[comment] => test comment
)
[5] => Array
(
[comment] => 111222
)
)
1
Unfortunally it print out only comment. I need to add other rows: queue,sum,sumAccD,sumAccC. Array must look like this:
Array
(
[6] => Array
(
[queue] => 5
[sum] => ''
....
[comment] => test comment
)
[5] => Array
(
[queue] => 2
[sum] => 2.1
....
[comment] => 111222
)
)
1
Please help merge them.
Thanks.
Look at this line:
$ret[$pvkey] = array($pkey => $pvval);
You're assigning the key to a new array every time, overwriting what was previously there.
In your case, 'comment' is the last key that is processed, so that's going to be the only key in the final array.
Instead of this, you could define a new array only once outside the inner for, like this:
$ret[$pvkey] = array();
And then assign your values to that array in the inner for loop as you would normally do (so no more creating arrays there!)
Problem solved by replacing
$ret[$pvkey] = array($pkey => $pvval);
with
$ret[$pvkey][$pkey] = $pvval;

Categories