PHP 过滤器 Json 对象
PHP Filter Json Object
我有这个 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。一旦您使用了一些单引号 ('
),这将真正起作用。然后你可以:
- 使用json_decode()解码数据
- 使用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"
}
}
我有这个 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。一旦您使用了一些单引号 ('
),这将真正起作用。然后你可以:
- 使用json_decode()解码数据
- 使用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"
}
}