Looping through an array in PHP not working as expected - php

I am retrieving the following array, which is the options list for a product, using the bigCommerece API. Using echo $curlProductOptions I see the following echoed to the screen:
[
{
"id": 412,
"option_id": 37,
"display_name": "testSteveMemory",
"sort_order": 0,
"is_required": true
},
{
"id": 413,
"option_id": 34,
"display_name": "Hard Drive (desktop)",
"sort_order": 1,
"is_required": true
},
{
"id": 414,
"option_id": 24,
"display_name": "Include Keyboard & Mouse",
"sort_order": 2,
"is_required": true
},
{
"id": 415,
"option_id": 33,
"display_name": "Memory",
"sort_order": 3,
"is_required": true
}
]
So I am presuming I have an array within $curlProductOptions containing the above data.
I now need to loop through each element and echo each 'option_id'.
I have tried :
foreach($curlProductOptions['option_id'] as $value)
{echo $value;}
and:
for ($i = 0; $i < count($curlProductOptions); ++$i)
{echo 'optionID ='.$curlProductOptions[$i].option_id.'<br>';}
I also tried just to echo one of the elements.
echo $curlProductOptions['option_id'][0];
echo $curlProductOptions[0]['option_id'];
What am I not understanding here?

You have json encoded string. So you need to json_decode first .
try like this:
$curlProductOptions = json_decode($curlProductOptions,true);//create associative array
foreach($curlProductOptions['option_id'] as $value){
echo $value;
}

This works fine for me:
$curlProductOptions = json_decode($curlProductOptions, true);
foreach($curlProductOptions as $value){
echo $value['option_id'];
}

Related

Pull nested JSON data using foreach loop in php

I want to pull data from below JSON format using PHP (foreach loop).
User detail is correspondence to house detail and house detail correspondence to individual meter reading.
I want to show Username, Device_No and all meter_detail field. Please help me out.
{
"id": 7,
"Username": "user",
"Housename": "Leela",
"Houses_list": [{
"id": 1,
"Device_No": 1111,
"meter_detail": [{
"id": 1,
"flow": 12,
"date": "2020-02-13T12:05:14.709Z",
"opening": 5,
"volume": 1234
},
{
"id": 2,
"flow": 32,
"date": "2020-02-13T12:05:26.821Z",
"opening": 2,
"volume": 1235
}
]
},
{
"id": 2,
"Device_No": 231,
"meter_detail": [{
"id": 3,
"flow": 78,
"date": "2020-02-13T12:05:41.331Z",
"opening": 5,
"volume": 7854
}]
}
]
}
You need to convert the JSON to an array by using json_decode(). Then a couple of foreach loops would do work for you:
<?php
$json = '{
"id": 7,
"Username": "user",
"Housename": "Leela",
"Houses_list": [{
"id": 1,
"Device_No": 1111,
"meter_detail": [{
"id": 1,
"flow": 12,
"date": "2020-02-13T12:05:14.709Z",
"opening": 5,
"volume": 1234
},
{
"id": 2,
"flow": 32,
"date": "2020-02-13T12:05:26.821Z",
"opening": 2,
"volume": 1235
}
]
},
{
"id": 2,
"Device_No": 231,
"meter_detail": [{
"id": 3,
"flow": 78,
"date": "2020-02-13T12:05:41.331Z",
"opening": 5,
"volume": 7854
}]
}
]
}';
$input = json_decode($json, true);
echo 'Username: '.$input['Username'].'<br>';
foreach ($input['Houses_list'] as $device){
echo '<br>Device No: '.$device['Device_No'].'<br>';
foreach ($device['meter_detail'] as $metrics){
echo '<table style="border: 1px solid black">';
foreach ($metrics as $key => $metric){
echo '<tr><td>'.$key.'</td><td>'.$metric.'</td></tr>';
}
echo '</table>';
}
}
?>
Output:

How to print json non array data [duplicate]

This question already has answers here:
How to extract and access data from JSON with PHP?
(1 answer)
Accessing JSON object elements in PHP
(1 answer)
Closed 4 years ago.
i have JSON data as bellow and want to print "Page" and "PageCount" using php let me know how can i do that.
{
"response": {
"Page": 1,
"PageCount": 1,
"RecordsSent": 1,
"RecordsFound": 1,
"Stock": [
{
"Colour": "OFF WHITE",
"Size": "S",
"Style": "A0000001",
"Article": "FLORAL 1",
"Size_Range": "S - 3XL",
"In_Stock": 58,
"Demand": 0,
"Supply": 2,
"Sell_Price9": 0
}
]
}
}
how can i print "Page" and "PageCount" only?
You can try this code:
$content = '{
"response": {
"Page": 1,
"PageCount": 1,
"RecordsSent": 1,
"RecordsFound": 1,
"Stock": [
{
"Colour": "OFF WHITE",
"Size": "S",
"Style": "A0000001",
"Article": "FLORAL 1",
"Size_Range": "S - 3XL",
"In_Stock": 58,
"Demand": 0,
"Supply": 2,
"Sell_Price9": 0
}
]
}
}';
$data = json_decode($content, true);
echo "Page:", $data['response']['Page'], "\n";
echo "PageCount:", $data['response']['PageCount'];
json_decode second param is
Assoc - When TRUE, returned objects will be converted into associative arrays.
That means, if assoc = false or not isset, than you have object:
echo "Page:", $data->response->Page, "\n";
echo "PageCount:", $data->response->PageCount;
You can parse it, like this: Live Demo
<?php
$json = '{
"response": {
"Page": 1,
"PageCount": 1,
"RecordsSent": 1,
"RecordsFound": 1,
"Stock": [
{
"Colour": "OFF WHITE",
"Size": "S",
"Style": "A0000001",
"Article": "FLORAL 1",
"Size_Range": "S - 3XL",
"In_Stock": 58,
"Demand": 0,
"Supply": 2,
"Sell_Price9": 0
}
]
}
}';
$decoded_json = json_decode($json);
echo "Page: ".$decoded_json->response->Page."<br/>";
echo "Page Count: ".$decoded_json->response->PageCount;

Delete object from json file with PHP

Well, I have a web project and I have to be saving things temporarily, I started work with a json file, so far I can add and update.
The json file looks like this:
[
{
"username": "Baldwin",
"products": [
{
"id": 0,
"amount": 10
},
{
"id": 1,
"amount": 9
},
{
"id": 2,
"amount": 9
}
]
},
{
"username": "Alice",
"products": [
{
"id": 0,
"amount": 11
},
{
"id": 1,
"amount": 13
},
{
"id": 2,
"amount": 6
}
]
},
{
"username": "Terry",
"products": [
{
"id": 0,
"amount": 12
},
{
"id": 1,
"amount": 14
},
{
"id": 2,
"amount": 5
}
]
}
]
The problem comes when I want to delete an specific array or when I want to delete it completely, I can do it and it works fine, but I have the doubt about why when I delete the object, other fields are add to the json file, like an id.
When i delete just one product inside of the "products" array something like this happen:
[
{
"username": "Baldwin",
"products": { "1": { "id": 1, "amount": 9 }, "2": { "id": 2, "amount": 9 } }
},
{
"username": "Alice",
"products": [
{ "id": 0, "amount": 11 },
{ "id": 1, "amount": 13 },
{ "id": 2, "amount": 6 }
]
},
{
"username": "Terry",
"products": [
{ "id": 0, "amount": 12 },
{ "id": 1, "amount": 14 },
{ "id": 2, "amount": 5 }
]
}
]
And when i delete a complete array from the json file, something like this happen:
{
"1": {
"username": "Alice",
"products": [
{ "id": 0, "amount": 11 },
{ "id": 1, "amount": 13 },
{ "id": 2, "amount": 6 }
]
},
"2": {
"username": "Terry",
"products": [
{ "id": 0, "amount": 12 },
{ "id": 1, "amount": 14 },
{ "id": 2, "amount": 5 }
]
}
}
My php file to delete:
<?php
// load file
$data = file_get_contents('results.json');
// decode json to associative array
$json_arr = json_decode($data, true);
$flag = false;
// We check if the user wants to delete all or just one product
if(isset($_POST["all"])):
$username = $_POST["username"];
foreach ($json_arr as $key => $value):
// find the username on the json file
if($value["username"] == $username):
unset($json_arr[$key]);
break;
endif;
endforeach;
elseif(isset($_POST["one"])):
$username = $_POST["username"];
$id = $_POST["id"];
foreach ($json_arr as $key => $value):
// find the username on the json file
if($value["username"] == $username):
// loop products of the current username
foreach ($json_arr[$key]["products"] as $k => $product):
// find the id of the product
if($json_arr[$key]["products"][$k]["id"] == (int)$id):
// delete the product
unset($json_arr[$key]["products"][$k]);
endif;
endforeach;
endif;
endforeach;
endif;
// encode json and save to file
file_put_contents('results.json', json_encode($json_arr));
// redirect to show.php
header("Location: show.php");
?>
I've been taking a look to questions like this one but i couldn't find something with php, i would like to know how to solve this or if this is normal.
What happens when you use unset($json_arr[0]) is that the first element is removed, but the keys are not updated. If you inspect the array after the removal, you'll find that your array has two elements, at $json_arr[1] and $json_arr[2].
When you then perform a json_encode($json_arr) on this, PHP's JSON decoder looks at the array and since arrays are supposed to begin at the 0th element but this array begins at 1, it decides that in order to preserve the keys, the array would have to be converted to an associative array - which transforms the integer array keys into string keys in JSON.
For a short and quick solution, you can try:
$json_arr = array_diff($json_arr, [$key]);
You could even use array_splice or array_values - see here for inspiration.

json file to php array. using json_decode gives null

I have the php file
<?php
$str = '{
"champions": [{
"id": 24,
"stats": {
"armor": 27.04,
"attackrange": 125.0,
}
}, {
"id": 37,
"stats": {
"armor": 20.544,
"attackrange": 550.0,
}
}],
"matches": [{
"timestamp": 1433644800,
"champion": 427,
"lane": "TOP"
}, {"timestamp": 1453702800,
"champion": 103,
"lane": "MIDDLE"
}]
}';
$array = json_decode($str,true);// read string to array (true means array, false means object)
var_dump($array);
$champions = $array["champions"];
var_dump($champions);
which outputs null for both var_dumps. What is my mistake? Thanks. Is it maybe a problem that there are square brakets in the json snippet?
You have errors in your JSON.
Remove , in the end of [champions][stats] arrays.
please remove comma separation from every last element of champions->stats like below then do decode
{
"champions": [
{
"id": 24,
"stats": {
"armor": 27.04,
"attackrange": 125
}
},
{
"id": 37,
"stats": {
"armor": 20.544,
"attackrange": 550
}
}
],
"matches": [
{
"timestamp": 1433644800,
"champion": 427,
"lane": "TOP"
},
{
"timestamp": 1453702800,
"champion": 103,
"lane": "MIDDLE"
}
]
}

How do I get all the keys in JSON within PHP?

How do I get all of the keys and loop through them, echoing each one, from a JSON object array?
Here is my code:
/* SAMPLE JSON THAT IS SENT
$mystring = '{
"display_name": "Silverware",
"fields": [
{
"field_name": "Age",
"sort_order": 1,
"required": 0,
"view_type": "text",
"description": "",
"multi_value": 0,
"char_count": 255
},
{
"field_name": "Brand",
"sort_order": 2,
"required": 0,
"view_type": "multiselect",
"description": "",
"multi_value": 1,
"char_count": 255
}
]
}';
*/
$json = json_decode($HTTP_RAW_POST_DATA);
$arr = $json->{'fields'};
// This is how I print a specific value
//print $arr[0]->{'field_name'};
Adding the following isn't working for me:
foreach ($arr as $k => $v) {
echo $k', ';
}
Use true for the second parameter of json_decode().
foreach ($j['fields'] as $field) {
$keys = array_keys($field);
foreach ($keys as $key) {
echo $key;
}
}

Categories