Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save bitlewis/7b98a716debeaec053fd724392bfb165 to your computer and use it in GitHub Desktop.
Save bitlewis/7b98a716debeaec053fd724392bfb165 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
*/
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment