简体   繁体   中英

How to extend a multidimensional array in php

if my code looks like...

$result = $mysqli->query("SELECT id, name, color FROM fruits");
$list = array();
while($r = $result->fetch_array()) {
    $list[] = $r;
}
print json_encode(array('list' => $list));

the result is...

list[0].id = '1', list[0].name = 'apple', list[0].color = 'red';
list[1].id = '2', list[1].name = 'banana', list[1].color = 'yellow';
...

It's fine, but i need additional infos in the list. How can i extend the arrays and get something like:

list[0].id = '1', list[0].name = 'apple', list[0].color = 'red', list[0].taste = 'sour';
list[1].id = '2', list[1].name = 'banana', list[1].color = 'yellow', list[0].taste = 'sweet';
...

This does not work:

$result = $mysqli->query("SELECT id, name, color FROM fruits");
$list = array();
while($r = $result->fetch_array()) {
    $list[] = $r;
    $list[]['taste'] =  'sweet'; //DOES NOT WORK
    array_push($list,array("taste" => 'sweet')); //DOES ALSO NOT WORK
}
print json_encode(array('list' => $list));

Thank you!!!

Because $list[] = $value is the same as array_push($list, $value) . There's no such thing as $list[]['key'] .

You should add it to the $r variable instead, before you add it to $list :

while($r = $result->fetch_array()) {
    $r['taste'] = 'sweet'; //DOES WORK!
    $list[] = $r;
}

If you already have $list , you can simply loop through and add it:

foreach ($list as &$array) {
    $array['taste'] = 'sweet';
}
unset($array); //remember to unset references

..or if you hate references:

foreach ($list as $key => $array) {
    $list[$key]['taste'] = 'sweet';
}

You need an intermediate variable

$result = $mysqli->query("SELECT id, name, color FROM fruits");
$list = array();
while($r = $result->fetch_array()) {
 $r['taste'] =  'sweet'; //Modify an existing array

 $list[] = $r;


}
print json_encode(array('list' => $list));

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM