I have a JSON item list in the database that holds the the serial number of different items to be printed according to the order of their serial number. The JSON structure is like this:
{
"item_list": [
{
"item_sl": "1",
"item_print": "flowers"
},
{
"item_sl": "2",
"item_print": "cars"
}
]
}
After retrieving it from the database, I decoded the items in $items_array
and then tried to create variables like $item1, $item2 ...
which I wanted to assign to the item_print
values from the JSON. The same print values have been already defined earlier ($cars, $flowers
). Lastly, I wanted to print all of them. The code is:
$cars = 'Tesla is my favorite.';
$flowers = 'I love all flowers.';
$items_array = json_decode($items_data, true);
foreach ($items_array['item_list'] as $item_list) {
foreach ($item_list['item_sl'] as $key => $n) {
${'item'.$n} = $item_list['item_print'][$key];
}
}
$all_print = $item1.' '.$item2;
echo $all_print;
But $all_print
is returning null, which tells me my approach is not correct. What am I missing here? What would be a better approach for printing the $cars and $flowers
variables according to the serial numbers from the JSON?
item1
and theitem2
anywhere that's whyall_print
is empty !!${'item'.$n} = $item_list['item_print'][$key];
creates something like$item1 = $flowers
?