Reputation: 704
I have a php script that is outputting a json response that looks something like this ( if it matters, the response below was outputted by a test ajax call ) ---
{
"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
}
},
So in my entries
I have duplicate values for body
and image
, but everything else seems fine.
In my script I am outputting my values like this for example -
$entries = $result->entries;
foreach ($entries as $ent){
echo $ent->image;
echo $ent->title;
echo $ent->body;
}
My problem is I dont want to output any entries with duplicate data, regardless if the title is different. If the image and body is a duplicate as another entry then I want to skip over it.
How can I achieve this?
EDIT
Exact JSON response structure from php print_r -
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] =>
)
)
Upvotes: 0
Views: 192
Reputation: 23958
You can use array_column to make the entries array associative and remove the duplicates.
$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'];
}
This way, when you loop to output you only have unique values.
You can also use array_unique but making the array associative can be beneficial in other ways.
If you want to delete duplicates according to both image and body then loop the array and make a compound associative keys.
$json = 'json string';
$arr = json_decode($json, true);
foreach($arr['entries'] as $e){
$ent[$e['body'] . " " . $e['image']] = $e;
}
$ent is now the new array with unique values of 'entries'
foreach ($ent as $e){
echo $e['image'];
echo $e['title'];
echo $e['body'];
}
Upvotes: 1