Skip to content

Instantly share code, notes, and snippets.

@chancesmith
Last active December 11, 2022 15:54
Show Gist options
  • Star 5 You must be signed in to star a gist
  • Fork 3 You must be signed in to fork a gist
  • Save chancesmith/8d21d966b69eff170fae7fa4e5cfb4f5 to your computer and use it in GitHub Desktop.
Save chancesmith/8d21d966b69eff170fae7fa4e5cfb4f5 to your computer and use it in GitHub Desktop.
Foreach loop through JSON object array
<?php
$json = '[
{
"categories": "10,11",
"title": "Promos",
"columns": "col-md-3"
},
{
"categories": "10,12",
"title": "Instructional",
"columns": "col-md-4"
},
{
"categories": "10,13",
"title": "Performance",
"columns": "col-md-4 col-lg-3"
}
]';
$queries = json_decode($json);
var_dump($json);
// string(266) "[ { "categories": "10,11", "title": "Promos", "columns": "col-md-3" }, { "categories": "10,12", "title": "Instructional", "columns": "col-md-4" }, { "categories": "10,13", "title": "Performance", "columns": "col-md-4 col-lg-3" } ]"
echo "<br><br>";
var_dump($queries);
// array(3) { [0]=> object(stdClass)#1 (3) { ["categories"]=> string(5) "10,11" ["title"]=> string(6) "Promos" ["columns"]=> string(8) "col-md-3" } [1]=> object(stdClass)#2 (3) { ["categories"]=> string(5) "10,12" ["title"]=> string(13) "Instructional" ["columns"]=> string(8) "col-md-4" } [2]=> object(stdClass)#3 (3) { ["categories"]=> string(5) "10,13" ["title"]=> string(11) "Performance" ["columns"]=> string(17) "col-md-4 col-lg-3" } }
echo "<br><br>";
//Example foreach
foreach($queries as $query){
// this is where your WP query_posts( $args ); will go
// this is how you'll access the array variables
echo "<br>Query: ";
echo $query->categories;
echo ", ";
echo $query->title;
echo ", ";
echo $query->columns;
echo "<br>";
}
/*
Query: 10,11, Promos, col-md-3
Query: 10,12, Instructional, col-md-4
Query: 10,13, Performance, col-md-4 col-lg-3
*/
@camilamoreiradev
Copy link

Thanks.

@majidorc
Copy link

Thank You :)
but I just have one more question for $json I use curl and API
on an array is false/true how can change to yes/no

@irwingb1979
Copy link

Thanks

@AbelGetu
Copy link

AbelGetu commented Feb 7, 2020

Thanks.

@theCoder505
Copy link

That was very helpful... Great and thanks...

@abankk2
Copy link

abankk2 commented Mar 3, 2022

Terimakasih Banyak

@bignimz
Copy link

bignimz commented Dec 11, 2022

Thanks

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment