1

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.

3
  • You're using the same variable $array for the original JSON array and the temporary array inside the loop. Commented Oct 22, 2021 at 18:33
  • Shouldn't you be pushing onto $categories, not $array? Commented Oct 22, 2021 at 18:34
  • None of your categories have any duplicates. And there's no need to use array_values, since $array isn't an associative array after explode(). Commented Oct 22, 2021 at 18:35

1 Answer 1

3

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);
Sign up to request clarification or add additional context in comments.

2 Comments

That worked, thank you. How do I then order then alphabetically? Use asort() ?
Sort the array with sort(). asort() is for associative arrays.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.