I have an array such as this which I get from a database query:
$arrname
Array (
[0] => stdClass Object (
[name] => Mike teach
[age] => 67
[gender] => Male
)
[1] => stdClass Object (
[name] => Logan Pierce
[age] => 45
[gender] => Male
)
[2] => stdClass Object (
[name] => Erikka Menh
[age] => 60
[gender] => Female
)
);
Now I want to append to this array and assuming they were like a 100 rows. I can't do that manually right? So I tried using this code:
foreach($arrname as $key => $value){
$line = json_decode($value);
$line['country'] = 'Us';
$line['occupation'] = 'Retired';
$arrname[$key] = json_encode($line);
}
echo $arrname[0]['country'];
Please I'd appreciate some help.
change this code:
foreach($arrname as $key => $value){
$line = json_decode($value);
$line['country'] = 'Us';
$line['occupation'] = 'Retired';
$arrname[$key] = json_encode($line);
}
echo $arrname[0]['country'];
to this:
foreach($arrname as $key => $value){
$line = (array) $value;
$line['country'] = 'Us';
$line['occupation'] = 'Retired';
$arrname[$key] = (object) $line;
}
echo $arrname[0]->country;
the json_encode function convert the array to a string type Javascript Object and json_decode does viceversa read http://php.net/manual/en/function.json-encode.php
If you wanna have a objects, you should use it like that
[1] => new stdClass Object (
'name' => 'Logan Pierce',
'age' => 45,
'gender' => 'Male'
)
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.