我有这个 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 数据中的字符串。一旦你使用了一些单引号 ( '
),这实际上会起作用。然后,您可以:
像这样:
$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"
}
}
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句