looping secondary json array, selecting specific array - php

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.

Related

foreach loop for multidimensional array in 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

Select individual column json in php

{
"responseData": {
"results": [
{
"title": "sobig",
"titleNoFormatting": "test",
},
{
"title": "test 2 ",
"titleNoFormatting": "test 2sd",
},
{
"title": "asdasdasda",
"titleNoFormatting": "asdasdasd",
},
{
"title": "A Warming",
"titleNoFormatting": "A Warming",
}
.
.
.
.
{
"title": "last thing",
"titleNoFormatting": "sada",
}
],
I have json files like this.
for($i=$veri1; $i <= $veri2; $i++) {
$uri = "http://test.com/json/".$i."/0";
$json = json_decode(file_get_contents($uri));
if($json->data->price >= $nakit && $json->data->odds >= $oran)
{
I'm getting some data with this code correctly from another json file.
i want get data from first json code, if "title" == "sobig" . How can I do that.
$json->responseData->results->title == sobig is not working. How can I get data if title is sobig
$json= json_decode($response, true);
foreach ($json['responseData']['results'] as $key => $value) {
if ($value == 'sobig') {
// found it
}
}
Try this example to see if this may fix your issue.
<?php
$json = '{ "responseData": {
"result" : [
{ "title": "sobig" , "titleNo":"test"},
{ "title": "loco" , "titleNo":"test"},
{ "title": "tom" , "titleNo":"test"}
]
}}';
$jsonDecoded = json_decode($json);
foreach ($jsonDecoded->responseData->result as $key => $value) {
var_dump($value); echo '<br>';
if($value->title == 'sobig'){
echo "we did it!!";
echo "<br>";
}
}
?>
I place a couple of var dumps so you can see the stucture of your object and why you need to use the foreach

how to create json from associate array

I am new to PHP. So bear with me. I have to fetch songs from db. I don't know how to initialize associate array in a for loop using keyValuePair. and also add status attribute to it.
What i want is
{
"status" : "true" ,// It tells whether day available or not
"data": [
{
"name": "Joe Bloggs",
"id": "203403465"
},
{
"name": "Fred Bloggs",
"id": "254706567"
},
{
"name": "Barny Rubble",
"id": "453363843"
},
{
"name": "Homer Simpson",
"id": "263508546"
}
]
}
My Code
$html = file_get_html('http://1stfold.com/taskbox/Farrukh/Zare/');
$output = array();// how to initialze it in for loop with keyValue pair
// Find all "A" tags and print their HREFs
foreach($html->find('.branded-page-v2-body a') as $e)
{
if (0 === strpos($e->href, '/watch?v'))
{
$output[] = $e->href . '<br>';
echo $e->href . '<br>';
}
}
echo json_encode($output);
Thanks in Advance.
You can add an array to the $output array, by simply changing this :
$output[] = $e->href . '<br>';
To this :
$output['data'][] = array('name' => $name_value, 'id' => $id_value);
This will push arrays to the the $output['data'] array.
You should add the "status" keyValuePair before the loop

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>';
}
}

Loop through JSON with php, and write to it. Output is null

My goal is to loop through each Item within the JSON and add an additional key called "modal" to each "Item", and the value paired with that key that would contain html. I stripped down my code below.
I'm able to add 'modal' to each 'Item', however the value somehow gets set to null, instead of the html I would like it to be.
JSON file:
{"Item":{
"thumbnail":"http://...",
"title": "Item title"
},
"Item":{
"thumbnail":"http://...",
"title": "Item title"
}}
php:
$json_a=json_decode($json, true);
foreach ($json_a['Item'] as &$obj){
$out = '<img src=\"' . $obj['thumbnail'] . '\">';
$out .= '<span>' . $obj['title'] . '</span>';
$obj['modal'] = $out; //value of $out doesn't get passed in, instead the value becomes null.
}
$json_a=json_encode($json_a);
print_r($json_a);
json output:
...{'modal': null}...
Edited the JSON to be valid. It comes from Amazon's product API, I shortened it for this example and made it invalid.
Your JSON is invalid. It is an object with duplicate keys ("Item"). You should use an array instead:
[
{
"thumbnail": "...",
"title": "..."
},
{
"thumbnail": "...",
"title": "..."
}
]
Then you can iterate over it and add 'modal' to all elements:
$json_a = json_decode($json, true);
foreach ($json_a as &$obj) {
$out = '<img src=\"' . $obj['thumbnail'] . '\">';
$out .= '<span>' . $obj['title'] . '</span>';
$obj['modal'] = $out;
}
$json_a = json_encode($json_a);
print_r($json_a);
Its simple your json is not valid
{
"Item": {
"thumbnail": "http://...",
"title": "Item title",
^---- This should not be here
},
"Item": {
^-------------- Duplicate name
"thumbnail": "http://...",
"title": "Item title",
^---- This should not be here
}
}
The main issue is that you need to generate your object or array properly using json_encode if you are using PHP for the generation

Categories