I have this array called $all_cats which outputs the following
Array(
[0] => WP_Term Object(
[term_id] => 386
[name] => Ales
[slug] => ales
[term_group] => 0
[term_taxonomy_id] => 386
[taxonomy] => product_cat
[description] =>
[parent] => 384
[count] => 10
[filter] => raw
)
[1] => WP_Term Object(
[term_id] => 385
[name] => Beers
[slug] => beers
[term_group] => 0
[term_taxonomy_id] => 385
[taxonomy] => product_cat
[description] =>
[parent] => 384
[count] => 10
[filter] => raw
)
)
I'm trying to add the "term_id" and "name" to an indexed multidimensional array so i can output the following -
Example A
Array
(
[0] => Array
(
[parent_cats] => Array
(
[id] => 385,
[name] => "Beers"
)
)
[1] => Array
(
[parent_cats] => Array
(
[id] => 386,
[name] => "Ales"
)
)
)
I've tried the following but cant seem to add each item to the same key. How can i add each term_id & name so it outputs like example A?
$full_cats = array();
foreach ($all_cats as $cat_term) {
$parent_termID = $cat_term->term_id;
$parent_title = $cat_term->name;
// this doesnt work
$full_cats[]['parent_cats']['id'] = $parent_termID;
$full_cats[]['parent_cats']['name'] = $parent_title;
// this doesnt work
array_push($full_cats[]['parent_cats']['id'],$parent_termID);
array_push($full_cats[]['parent_cats']['name'],$parent_title);
}
How can i add each term_id & name so it outputs like example A?
CodePudding user response:
$full_cats = array();
foreach ($all_cats as $cat_term) {
$parent_termID = $cat_term->term_id;
$parent_title = $cat_term->name;
// this doesnt work
$full_cats[]=array(
"parent_cats"=>array(
"id" => $parent_termID,
"name" => $parent_title
)
);
}
The above code should work
- You need to learn the structure of multi and assoc array
CodePudding user response:
$full_cats = array();
$indx = 0;
foreach ($all_cats as $cat_term) {
$parent_termID = $cat_term->term_id;
$parent_title = $cat_term->name;
// this doesnt work
$full_cats[$indx]['parent_cats']['id'] = $parent_termID;
$full_cats[$indx]['parent_cats']['name'] = $parent_title;
$indx ;
// this doesnt work
// array_push($full_cats[]['parent_cats']['id'],$parent_termID);
// array_push($full_cats[]['parent_cats']['name'],$parent_title);
}