I have the following object:
"themes": [
{
"name": "Anchor",
"categories": "Creative, Portfolio",
},
{
"name": "Agensy",
"categories": "Creative, Portfolio",
},
{
"name": "Serenity Pro",
"categories": "One-Page, Multipurpose, Business, Landing Page",
},
{
"name": "Integral Pro",
"categories": "One-Page, Multipurpose, Business, Landing Page",
}
]
I want to iterate through each array and collect the values of the categories key
Then remove duplicates and spit out an array of unique category names.
I have the following code:
$json = $this->curl_get_marketplace_contents();
$array = json_decode($json, true);
$categories = array();
foreach ($array['themes'] as $theme) {
$array = explode(",", $theme['categories']);
$array = array_map('trim', $array);
$array = array_values($array);
$array = array_unique($array);
$categories = array_push($array, $categories);
};
return $categories;
But it's not working. It returns empty.
I feel like I'm close but I'm making a noob mistake. If anybody can point me in the right direction that would be great.
CodePudding user response:
Use array_merge()
to combine arrays, not array_push()
.
Remove the duplicates at the end after merging everything.
$json = $this->curl_get_marketplace_contents();
$data = json_decode($json, true);
$categories = array();
foreach ($data['themes'] as $theme) {
$array = explode(",", $theme['categories']);
$array = array_map('trim', $array);
$categories = array_merge($array, $categories);
};
return array_unique($categories);