PHP过滤器Json对象



我有这个json对象:

$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"
}
]
"

我想要得到parent_id不为0的类别。有人知道怎么做吗?

首先,您对所有内容使用双引号("),这将不起作用,因为PHP将不知道哪一部分是您的字符串,哪一部分只是JSON-data中的字符串。一旦您使用一些单引号('),这实际上就会起作用。然后可以:

  1. 使用json_decode()解码数据
  2. 使用array_filter()来过滤

:

$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);

输出:

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"
}
}

示例:https://3v4l.org/5psNk

最新更新