Foreach from array json data - php

I get an array in JSON format and I decode this data. I can access to single data by selecting e.g. echo $myArray[0]["name"];
However, I want to do a loop to iterate all names and prices from the array. Can you support me to find the bug in my code?
$url = "myurl";
$response = file_get_contents($url);
$myArray = json_decode($response, true);
foreach ($myArray as $product) {
echo $product->name . '<br>';
}
and here is a sample of the array:
[{
"id": 782,
"name": "Test Translation New",
"price": "1",
"image": {
"url": "xxx/image-2.jpg",
"position": 0
},
"link": "https:xxx",
"nickname": "newmarker"
}, {
"id": 777,
"name": "Test Translation",
"price": "0",
"image": {
"url": "https:xxx/image-1.jpg",
"position": 0
},
"link": "https:xxx",
"nickname": "newmarker"
}]

You are using json_decode(..., true), so the returned $myArray is an array, and all its sub items are all arrays.
<?php
$response = '
[{
"id": 782,
"name": "Test Translation New",
"price": "1",
"image": {
"url": "xxx/image-2.jpg",
"position": 0
},
"link": "https:xxx",
"nickname": "newmarker"
}, {
"id": 777,
"name": "Test Translation",
"price": "0",
"image": {
"url": "https:xxx/image-1.jpg",
"position": 0
},
"link": "https:xxx",
"nickname": "newmarker"
}]
';
$myArray = json_decode($response, true);
foreach ($myArray as $product) {
echo $product['name'] . "<br>\n";
}
Output:
Test Translation New<br>
Test Translation<br>

If the second argument of json_decode is given and it is true then the returned structure is an associative array. That being said you may print the names and prices like:
foreach ($myArray as $product) {
echo $product['name'] . ' - ' . $product['price'] . '<br>';
}

If the second argument of json_decode is given and it is true then the returned structure is an associative array. That being said you may print the names and prices like:
foreach ($myArray as $product) {
echo $product['name'];
echo (int) $product['price'];
}
or you can also do
foreach ($myArray as $product) {
echo "{$product['name']} - {$product['price']} <br />";
}

Related

How to show multiple array values in one row of php table

I have return data like below json object,
{
"user_token": "ad48c412-3866-4ac9-adf6-3328911ae46c",
"order_info": {
"order_id": "CGC12345678",
"company_id": 32,
"price": 1000.5,
"currency": "MYR",
"products": [
{ "type": "hr_claims", "name": "HR Claims", "is_fixed_price": true, "price": 500.5, "currency": "MYR" },
{ "type": "hr_leave", "name": "HR Leave", "is_fixed_price": true, "price": 500, "currency": "MYR" },
{ "type": "finance_advisory", "name": "FinanceAdvisory", "is_fixed_price": false, "currency": "MYR" }
],
"total_invoices": 200,
"total_staffs": 80
}
}
i want to save this one object in php table one row but since products have 3 different array i cannot get all 3 [products][name] in to one record in php table.
Like below
products - HR Claims, HR Leave, Finance Advisory
Can someone help me?
This is i try! This one return last one!
<td>
#php
$json = $order->data;
$json = json_decode($json, true);
$products = $json['order_info']['products'];
foreach ($products as $hitsIndex => $hitsValue) {
$data = $hitsValue['name']. '<br/>';
}
#endphp
{{$data}}
</td>
In your foreach loop you overwrite $data on every iteration, that's why you only get the last entry. You need to concatenate your results to $data.
Change
foreach ($products as $hitsIndex => $hitsValue) {
$data = $hitsValue['name']. '<br />';
}
to
$data = '';
foreach ($products as $hitsIndex => $hitsValue) {
$data .= $hitsValue['name']. '<br />';
}

How to decode this json with foreach

This is the JSON
{
"circuit_list": [
{
"_id": "58c0f378a986f808cdaf94cf",
"aggregation": {
"dev_name": "ME2-D2-BOO",
"port": {
"desc": "AKSES_SITE_SITE-TSEL_ME2-D2-BOO#1/2/5_200M_BOO082#CIPAKUBOO534",
"name": "1/2/5"
}
},
"area": "AREA 2",
"site_id": "N/A",
"site_name": "N/A"
},
{
"_id": "58c0f378a986f808cdaf94d0",
"aggregation": {
"dev_name": "ME2-D2-BOO",
"port": {
"desc": "AKSES_SITE_SITE-TSEL_ME2-D2-BOO#1/2/5_200M_BOO082#CIPAKUBOO534",
"name": "1/2/5"
}
},
"area": "AREA 2",
"site_id": "N/A",
"site_name": "N/A"
}
}
I already try with this code
$json = json_decode($url, true);
foreach($json as $value)
{
$_id = $value->_id;
}
it didn't work. Please help, I need to get the value to show them on the view. Did I do this wrong? this json is difficult because i didn't understand the structure.
I usually decode json with format
[{"id":"1","name":"faisal"}]
like this and with my foreach it's working.
If the second parameter of json_decode is true, the function will return an array instead of an object. Also, you would need to loop over the circuit_list property of the object.
$json = json_decode($url); // <- remove the parameter
foreach($json->circuit_list as $value) // <- loop over circuit_list
{
$_id = $value->_id;
}
<?php
$json = json_decode($url,true);
foreach($json['circuit_list'] as $value)
{
$id = $value['_id'];
}
?>

Laravel - Format JSON

I have a code that outputs the json result below:
{
"Ghost in the Shell": {
"id": 1203,
"Pipeline": {
"id": 6144,
"name": "Pipeline",
"status": "New",
"item_id": 5962,
"TotalTasksOpen": 2
}
}
}
Now how can I format it in the my desired json format below:
Note* I have to remove some result.
{
"Ghost in the Shell":
"id": 6144,
"name": "Pipeline",
"status": "New",
"item_id": 5962,
"TotalTasksOpen": 2
}
Will appreciate if anyone can help me please.
I am not sure what is your purpose , but here is what you need
<?php
$json = '{
"Ghost in the Shell": {
"id": 1203,
"Pipeline": {
"id": 6144,
"name": "Pipeline",
"status": "New",
"item_id": 5962,
"TotalTasksOpen": 2
}
}
}';
$array = json_decode($json, true);
$newArray = array();
foreach($array as $key=>$value) {
$newArray[$key] = '';
foreach($value as $k=>$v) {
if(is_array($v)) {
$newArray = array_merge($newArray,$v);
}
}
}
$newJson = json_encode($newArray);
echo $newJson;
?>

Separate json labels and values with php

I have accessed this json file on my website:
[{
"01:03:2016": "410",
"02:03:2016": "200",
"03:03:2016": "380"
}]
I want to use PHP to change the formatting to something like this, where the dates and counts are all values:
[{
"date": "01:03:2016",
"count": "410"
},
{
"date": "02:03:2016",
"count": "200"
},
{
"date": "03:03:2016",
"count": "380"
}]
PHP
$string = file_get_contents("data.json"); // your current json data
$json_a = json_decode($string, true);
$new_json = array();
foreach ($json_a as $key => $value) {
$new_json[] = array("date"=>$key,'count'=>$value);
}
echo json_encode($new_json); //output
data.json file (your current data)
[{
"01:03:2016": "410",
"02:03:2016": "200",
"03:03:2016": "380"
}]

how to loop through a Json responce

I have web page which get Json responce like this
{
'hotel_1page':[
{
'id':'10',
'name':'fsf',
'telephone':'233333'
},
{
'id':'11',
'name':'setttttt',
'telephone':'213123123'
},
{
'id':'12',
'name':'fsdfsdf',
'telephone':'122212121'
},
{
'id':'13',
'name':'xxcvcxv',
'telephone':'2147483647'
},
{
'id':'14',
'name':'dssdfg',
'telephone':'2147483647'
},
{
'id':'15',
'name':'dfsdfsdf',
'telephone':'21312321'
},
{
'id':'16',
'name':'fx_test_nw1',
'telephone':'23232323'
},
{
'id':'17',
'name':'fx_test_nw2',
'telephone':'31313131'
}
]
}
and i want to loop through this data and get this data to array and display as html how can i achieve this
this is where i get get json responce,and when i var_dump json encoded variable it says null,where $json variable shows the json responce,
$json = file_get_contents('http://www.example.com/hotel_list.php');
var_dump($json);
$array = json_decode($json, true);
var_dump($array);
The json that you are trying to parse is invalid. Change the single quotes to double quotes and you should be able to parse it to an array.
The JSON documentation says
A value can be a string in double quotes, or a number, or true or false or null, or an object or an array. These structures can be nested.
This should work:
$json = '{ "hotel_1page": [ { "id": "10", "name": "fsf", "telephone": "233333" }, { "id": "11", "name": "setttttt", "telephone": "213123123" }, { "id": "12", "name": "fsdfsdf", "telephone": "122212121" }, { "id": "13", "name": "xxcvcxv", "telephone": "2147483647" }, { "id": "14", "name": "dssdfg", "telephone": "2147483647" }, { "id": "15", "name": "dfsdfsdf", "telephone": "21312321" }, { "id": "16", "name": "fx_test_nw1", "telephone": "23232323" }, { "id": "17", "name": "fx_test_nw2", "telephone": "31313131" } ] }';
echo '<pre>';
var_dump(json_decode($json, true));
echo '</pre>';
I replaced all single quotes with double quotes, that did the trick.
I used single quotes before which caused json_decode to return null
[Edit for usage]
To use the data, you could use something like this:
$obj = json_decode($json, true);
foreach($obj as $row)
{
foreach($row as $key => $item)
{
// $item['id']
// $item['name']
// $item['telephone']
}
}
I'm using a nested foreach() because the id, name and telephone are an array within the hotel_page1 array

Categories