我有一个php脚本,正在输出一个类似以下内容的json响应(如果重要的话,下面的响应是通过一个测试ajax调用输出的)---
{
"type": "the type",
"typesm": "type of",
"entries": [
{
"title": "title one",
"body": "Original text",
"image": "image 1 url",
"time": "1558532690",
"meta": {
"mainColor": "#100a0e",
"adSpace": null
}
},
{
"title": "title two",
"body": "Original text",
"image": "image 1 url",
"time": "1558515409",
"meta": {
"mainColor": "#100a0e",
"adSpace": null
}
},
因此,在我的entries
中,我有body
和image
的重复值,但其他一切似乎都没问题。
在我的脚本中,例如,我正在输出我的值-
$entries = $result->entries;
foreach ($entries as $ent){
echo $ent->image;
echo $ent->title;
echo $ent->body;
}
我的问题是我不想输出任何重复数据的条目,无论标题是否不同。如果图像和正文与另一个条目重复,那么我想跳过它。
我该如何实现?
编辑
来自php print_r的精确JSON响应结构-
stdClass Object
(
[type] => game
[typesm] => br
[entries] => Array
(
[0] => stdClass Object
(
[title] => Hang Time Bundle
[body] => Score big when you cop the Hang Time Bundle, available now in the Item Shop. Unlock new Styles with Creative Mode Challenges.
[image] => https://imageurl.jpeg
[time] => 1558532690
[meta] => stdClass Object
(
[mainColor] => #100a0e
[adSpace] =>
)
)
[1] => stdClass Object
(
[title] => Hang Time Set
[body] => Score big when you cop the Hang Time Bundle, available now in the Item Shop. Unlock new Styles with Creative Mode Challenges.
[image] => https://imageurl.jpeg
[time] => 1558515409
[meta] => stdClass Object
(
[mainColor] => #100a0e
[adSpace] =>
)
)
答案 0 :(得分:2)
您可以使用array_column将条目与数组关联,并删除重复项。
$json = 'json string';
$arr = json_decode($json, true);
$arr['entries'] = array_column($arr['entries'], null, 'body');
foreach ($arr['entries'] as $ent){
echo $ent['image'];
echo $ent['title'];
echo $ent['body'];
}
这样,当您循环输出时,只有唯一的值。
您也可以使用array_unique,但是将数组关联起来可以通过其他方式带来好处。
如果要根据图像和正文删除重复项,则循环数组并创建复合关联键。
$json = 'json string';
$arr = json_decode($json, true);
foreach($arr['entries'] as $e){
$ent[$e['body'] . " " . $e['image']] = $e;
}
$ ent现在是具有唯一值“ entries”的新数组
foreach ($ent as $e){
echo $e['image'];
echo $e['title'];
echo $e['body'];
}