-2

I have this json object:

$categories = "
[
   {
      "id":5,
      "parent_id":0,
      "image_url":"https://files.cdn.printful.com/o/upload/catalog_category/77/7776d01e716d80e3ffbdebbf3db6b198_t?v=1652883254",
      "title":"Home & living"
   },
   {
      "id":6,
      "parent_id":1,
      "image_url":"https://files.cdn.printful.com/o/upload/catalog_category/4b/4b37924aaa8e264d1d3cd2a54beb6436_t?v=1652883254",
      "title":"All shirts"
   }
]
"

And I would like to get the categories that parent_id is not 0. Does any one know how can I do that?

Kraier
  • 101
  • 1
  • 1
  • 6

1 Answers1

2

First of all, you use double quotes (") for everything, which will not work since PHP will not know which part is your string and which part is only a string in the JSON-data. Once you use some single quotes ('), this will actually work. You can then:

  1. use json_decode() to decode the data
  2. use array_filter() to filter it

like this:

$categories = '
[
   {
      "id":5,
      "parent_id":0,
      "image_url":"https://files.cdn.printful.com/o/upload/catalog_category/77/7776d01e716d80e3ffbdebbf3db6b198_t?v=1652883254",
      "title":"Home & living"
   },
   {
      "id":6,
      "parent_id":1,
      "image_url":"https://files.cdn.printful.com/o/upload/catalog_category/4b/4b37924aaa8e264d1d3cd2a54beb6436_t?v=1652883254",
      "title":"All shirts"
   }
]
';

$data = json_decode($categories, true);

$relevant = array_filter($data, function($entry) {
   return $entry['parent_id'] !== 0;
});

var_dump($relevant);

output:

array(1) {
  [1]=>
  array(4) {
    ["id"]=>
    int(6)
    ["parent_id"]=>
    int(1)
    ["image_url"]=>
    string(107) "https://files.cdn.printful.com/o/upload/catalog_category/4b/4b37924aaa8e264d1d3cd2a54beb6436_t?v=1652883254"
    ["title"]=>
    string(10) "All shirts"
  }
}

example: https://3v4l.org/5psNk

ArSeN
  • 5,133
  • 3
  • 19
  • 26