foreach loop for multidimensional array in php - php

I have a multidimensional array with key value. I want to loop the data in that array but I don't know how.
This is my array:
{
"success": "1",
"order_details": [
{
"item_order": 5,
"address": "155, Mani Nagar Society, Nana Varachha, Surat, Gujarat 395006, India",
"contact": "95303709",
"total_price": "3330.0",
"order_place": "18-05-25 06-07-20",
"preparing_date_time": "",
"preparing_status": "Deactivate",
"dispatched_date_time": "",
"dispatched_status": "Deactivate",
"delivered_date_time": "",
"delivered_status": "Deactivate",
"menu": [
{
"menu_name": "demo item",
"item_amt": "200",
"Ingredients": [
{
"ingredients_name": "burger",
"ingredients_price": "200"
},
{
"ingredients_name": "pizza1",
"ingredients_price": "800"
}
]
}
]
}
]
}
How do I loop / foreach that array?
I guess there is a foreach inside a foreach, but I don't know how to do that.

In the manual of array_walk_recursive there is an example that might suit you.
http://php.net/manual/en/function.array-walk-recursive.php
$arr = json_decode($str, true); //$str is your json string
array_walk_recursive($arr, 'test_print');
function test_print($item, $key)
{
echo "[$key]: $item\n";
}
https://3v4l.org/dVUMS
If you only want to output some elements of the array you can create an array with the items you want to output and pass it on the function.
Then use in_array to see if it's a output or not.
https://3v4l.org/8ZvUS

Use this code:
<?php
$jsonData = '{
"success": "1",
"order_details": [
{
"item_order": 5,
"address": "155, Mani Nagar Society, Nana Varachha, Surat, Gujarat 395006, India",
"contact": "95303709",
"total_price": "3330.0",
"order_place": "18-05-25 06-07-20",
"preparing_date_time": "",
"preparing_status": "Deactivate",
"dispatched_date_time": "",
"dispatched_status": "Deactivate",
"delivered_date_time": "",
"delivered_status": "Deactivate",
"menu": [
{
"menu_name": "demo item",
"item_amt": "200",
"Ingredients": [
{
"ingredients_name": "burger",
"ingredients_price": "200"
},
{
"ingredients_name": "pizza1",
"ingredients_price": "800"
}
]
}
]
}
]
}';
$jsonDecode = json_decode($jsonData);
foreach ($jsonDecode->order_details as $orderDetail) {
echo "Item order: " . $orderDetail->item_order;
echo "<br>";
echo "Address: " . $orderDetail->address;
echo "<br>";
echo "Contact: " . $orderDetail->contact;
echo "<br>";
foreach ($orderDetail->menu as $menuItem) {
echo "Menu Name: " . $menuItem->menu_name;
echo "<br>";
echo "Item amt: " . $menuItem->item_amt;
echo "<br>";
foreach ($menuItem->Ingredients as $ingredientsItem) {
echo "Ingredients name: " . $ingredientsItem->ingredients_name;
echo "<br>";
echo "Ingredients price: " . $ingredientsItem->ingredients_price;
echo "<br>";
}
}
}
Output:
Item order: 5
Address: 155, Mani Nagar Society, Nana Varachha, Surat, Gujarat 395006, India
Contact: 95303709
Menu Name: demo item
Item amt: 200
Ingredient name: burger
Ingredient price: 200
Ingredient name: pizza1
Ingredient price: 800

Related

Foreach from array json data

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 />";
}

json-php giving filed out put two times?

There is records about the login_ids in json array. I want to fetch required results in json-php decode function. It is giving the login_id two times on top and bottom for each row. I there any way not to print the login_id in the value filed? The code details are given below.
<?php
$json = '{"records" :
[
{
"Name": "Jhon",
"Age": "45",
"Place": "Kettle",
"Phone": "9834453",
"log_id": "216"
},
{
"Name": "Bill",
"Age": "41",
"Place": "Ottava",
"Phone": "4513453",
"log_id": "215"
},
{
"Name": "James",
"Age": "39",
"Place": "Mexico",
"Phone": "3456734",
"log_id": "217"
},
{
"Name": "larry",
"Age": "51",
"Place": "New city",
"Phone": "34890453",
"log_id": "213"
}
]
}';
$myjson = json_decode($json, true); // decode the json string to an array
foreach ( $myjson['records'] as $row ) { // loop the records
echo 'Details of login id: '. $row['log_id']. '<br/>';
foreach ( $row as $field => $value ) { // loop the fields
echo $field . ': '. $value . '<br>';
}
echo '<br/>';
}
?>
Also is there any simple method to print the required login id (i.e where the login_id="217") so that the address of one person is given out put.
Following code my be better but not tested.
foreach ( $myjson['records'] as $row ) {
if ($row['log_id'] =='216') { // login id to be checked
echo 'Details of login id: '. $row['log_id']. '<br/>';
foreach ( $row as $field => $value ) { // loop the fields
if ($field != "log_id") { // hide the login id t bottom
echo $field . ': ' . $value . '<br>';
}
}
echo '<br/>';
}
}
Test the field name before printing it.
foreach ($row as $field => $value {
if ($field != "log_id") {
echo $field . ': ' . $value . '<br>';
}
}

How to set correct $key=>$value association in a JSON file using PHP or jQuery

I need to reformat my JSON file so that a value that's in an array, is now the key to that array.
Turn
{
"ID": "M-420",
"ProductName": "example product name ",
"ProductDescription": "example description",
"Color": "blue "
},
{
"ID": "M-421",
"ProductName": "example product name ",
"ProductDescription": "example description",
"Color": "yellow "
}
Into
{
"M-420": {
"ProductName": "example product name ",
"ProductDescription": "example description",
"Color": "blue "
}
},
{
"M-421": {
"ProductName": "example product name ",
"ProductDescription": "example description",
"Color": "blue "
}
}
I need to be able to grab the properties of each unique ID using PHP. I'm converting my JSON into an associative array using $json_decode();
Much appreciated!
$new_array = array();
foreach ($array as $element) {
$new_array[$element['ID']] = $element;
}
Quite simple solution would be this:
$json_obj_old = json_decode($json_before_process);
$json_obj_new = array();
foreach($json_obj_old as $json_element){
$json_obj_new[$json_element['ID']] = $json_element;
unset($json_obj_new[$json_element['ID']]['ID']);
}
return json_encode($json_obj_new);

looping secondary json array, selecting specific array

I recently asked a question about looping an array which was answered and worked with this:
Answer Marked.
My own modified Answer is below too.
JSON
{"product": [{
"title":"Product One",
"price":"Price One",
"desc":"Description One"
}]
}
PHP
foreach($product['product'] as $value) {
echo "Title : " .$value['title'];
}
I've been trying to figure out how to loop a second level(?) array such as this image array.
JSON
{"product": [{
"title":"Product One",
"price":"Price One",
"desc":"Description One",
"image": [{
"img":"image 1 1"
},{
"img":"image 1 2"
},{
"img":"image 1 3"
}]
}, {
"title":"Product Two",
"price":"Price Two",
"desc":"Description Two",
"image": [{
"img":"image 2 1"
},{
"img":"image 2 2"
},{
"img":"image 2 3"
}]
}]
}
So far I've tried this:
<?php
foreach($product['product']['image'] as $value) {
echo "Image: " .$value['img'] . "<br>";
}
?>
and
<?php
foreach($product['product'] as $value) {
echo "Image: " .$value['image']['img'] . "<br>";
}
?>
As well as a few variations of similar ideas.
My desired output is:
Image: image 1 1
Image: image 1 2
Image: image 1 3
Image: image 2 1
Image: image 2 2
Image: image 2 3
Also, how would I go about selecting an array via a value eg..
JSON
{"product": [{
"id":"001"
"title":"Product One",
"price":"Price One",
"desc":"Description One"
},{
"id":"002"
"title":"Product One",
"price":"Price One",
"desc":"Description One"
}]
}
PHP
if ( isset( $product['product']['id'] && $product['product']['id'] == "001") ) {
foreach(*specific array as $value) {
echo "Title : " .$value['title'] . "<br>";
echo "Price : " .$value['price'] . "<br>";
}
etc..
I was thinking a better way would be to set the array as the id so I can just say go grab array {"product": [{"001": [{"title:..."002": [{... instead of product with a value of 001 for the key id. Just not sure about a lot of things so it's hard to find my errors.
Thanks in advance.
For the first section you can use following;
<?php
foreach($product['product'] as $value) {
foreach($value["image"] as $image) {
echo "Image: " .$image['img'] . "<br>";
}
}
?>
Here is a working demo: Demo
For the second part you can use following;
function getArrValue($key, &$product) {
foreach ($product["product"] as $product) {
if (!empty($product["id"]) && $product["id"] == $key) {
return $product;
}
}
}
var_dump(getArrValue("001", $product));
You can see demo here: Demo
You will need to iterate over the first dimension before you can iterate over the second dimension:
foreach ($data['product'] as $product) {
//echo "Title : " . $product['title'] . "\n";
foreach ($product['image'] as $image) {
echo "Image: {$image['img']}\n";
}
}
You can use $key=>$value to get property name
foreach($product['product'] as $key=>$value){
if ($key =="image"){
foreach($value as $img){
echo "Image: ".$img;
}
}
}
Figured out a small solution which fits my needs based off paulitto's answer.
PHP
foreach($product['product'] as $key=>$value){
if ($value['id'] =="001") {
echo "Title: " .$value['title']."<br>";
foreach($value['image'] as $img){
echo "Image: " .$img['img']."<br>";
}
}
}
OUTPUT
Title: Product One
Image: image 1 1
Image: image 1 2
Image: image 1 3
Thanks everyone.

How to retrieve values from multilevel json

Im trying to get the values from the various sections of this json entry.
{
"gallery_show": "1",
"gallery": {
"path": ["images\/slide2.jpg", "images\/slide1.jpg", "images\/slide2.jpg", "images\/slide1.jpg", "images\/slide2.jpg", "images\/slide1.jpg"],
"title": ["", "", "", "", "", ""],
"caption": ["", "", "", "", "", ""],
"thumb": ["\/admin\/cache\/thumbs_200x150\/slide2_200x150.jpg",
"\/admin\/cache\/thumbs_200x150\/slide1_200x150.jpg",
"\/admin\/cache\/thumbs_200x150\/slide2_200x150.jpg",
"\/admin\/cache\/thumbs_200x150\/slide1_200x150.jpg",
"\/admin\/cache\/thumbs_200x150\/slide2_200x150.jpg",
"\/admin\/cache\/thumbs_200x150\/slide1_200x150.jpg"]
},
"videos_show": "1",
"videos": {
"title": ["Arnie", "Arnie", "Arnie", "Arnie", "Arnie"],
"sharelink": ["http:\/\/youtu.be\/7kTz6MVrBlY", "http:\/\/youtu.be\/7kTz6MVrBlY", "http:\/\/youtu.be\/7kTz6MVrBlY", "http:\/\/youtu.be\/7kTz6MVrBlY", "http:\/\/youtu.be\/7kTz6MVrBlY"]
},
"attachments_show": "1",
"attachments": {
"path": ["images\/slide2.jpg", "images\/slide1.jpg"],
"title": ["Attchment", "Attchment"],
"caption": ["Attachment Description", "Attachment Description"]
},
"links_show": "1",
"links": {
"title": ["Link1", "Link2"],
"httplink": ["http:\/\/www.mydomain.com", "http:\/\/www.mydomain.com"],
"targetlink": ["_blank", "_blank"]
}
}
If i use this method
$entries= json_decode($this->item->entries);
and then i echo this
echo $entries->gallery_show;
I get the desired result = 1
But how do i now get the things beneath it if gallery_show=1 and display them as values i can use inside my php?
Any help for this old brain would be much appreciated.
Cheers in advance
Jonny
You could do somewhat like this...
$arr = json_decode($json);
foreach($arr as $k=>$v)
{
if($k=='gallery_show' && $v==1)
{
foreach($arr->gallery->path as $path)
{
echo "<img src=$path />";
}
break;
}
}
Demo
Code update..
$arr = json_decode($json);
$i=0;
foreach($arr as $k=>$v)
{
if($k=='gallery_show' && $v==1)
{
foreach($arr->gallery as $gall)
{
echo "Title :".$arr->gallery->title[$i]."<br/>";
echo "Caption :".$arr->gallery->caption[$i]."<br/>";
echo "Thumbnail :".$arr->gallery->thumb[$i]."<br>";
echo "<img src=".$arr->gallery->path[$i]." /><br>";
$i++;
}
break;
}
}
Demo

Categories