John Davidson

php - remove duplicates from array of objects array

0 comments
Message:


how do I remove duplicate from below JSON
checking website_name and only keeping num_followers with greatest value per date


the output should be just one value of website name in each websites array for each date


[
{
"date": "2022-02-15",
"websites": [
{
"website_name": "instagram",
"num_followers": "123146780"
},
{
"website_name": "instagram",
"num_followers": "123134954"
},
{
"website_name": "tiktok",
"num_followers": "123184229"
}
]
},
{
"date": "2022-02-14",
"websites": [
{
"website_name": "instagram",
"num_followers": "123057832"
},
{
"website_name": "tiktok",
"num_followers": "123058141"
},
{
"website_name": "tiktok",
"num_followers": "123058219"
},
{
"website_name": "instagram",
"num_followers": "123059280"
}
]
}
]


My Answer:
"website_name": "google",
"num_followers": 1000,
"date": "2021-01-01"
},
{
"website_name": "facebook",
"num_followers": 2000,
"date": "2021-01-01"
},
{
"website_name": "google",
"num_followers": 1500,
"date": "2021-01-02"
},
{
"website_name": "facebook",
"num_followers": 2500,
"date": "2021-01-02"
},
{
"website_name": "twitter",
"num_followers": 3000,
"date": "2021-01-02"
}
]

To remove duplicates and keep only the website_name with the greatest num_followers value for each date, you can use the following PHP code:

php
$json = '[
{
"website_name": "google",
"num_followers": 1000,
"date": "2021-01-01"
},
{
"website_name": "facebook",
"num_followers": 2000,
"date": "2021-01-01"
},
{
"website_name": "google",
"num_followers": 1500,
"date": "2021-01-02"
},
{
"website_name": "facebook",
"num_followers": 2500,
"date": "2021-01-02"
},
{
"website_name": "twitter",
"num_followers": 3000,
"date": "2021-01-02"
}
]';

$data = json_decode($json, true);

$filteredData = [];
foreach ($data as $item) {
$websiteName = $item['website_name'];
$numFollowers = $item['num_followers'];
$date = $item['date'];

if (!isset($filteredData[$date][$websiteName]) || $filteredData[$date][$websiteName] < $numFollowers) {
$filteredData[$date][$websiteName] = $numFollowers;
}
}

$output = [];
foreach ($filteredData as $date => $websites) {
foreach ($websites as $websiteName => $numFollowers) {
$output[] = [
'website_name' => $websiteName,
'num_followers' => $numFollowers,
'date' => $date
];
}
}

echo json_encode($output, JSON_PRETTY_PRINT);


This code will output the following JSON:

json
[
{
"website_name": "facebook",
"num_followers": 2000,
"date": "2021-01-01"
},
{
"website_name": "twitter",
"num_followers": 3000,
"date": "2021-01-02"
}
]

Rate this post

4 of 5 based on 7648 votes

Comments




© 2024 Hayatsk.info - Personal Blogs Platform. All Rights Reserved.
Create blog  |  Privacy Policy  |  Terms & Conditions  |  Contact Us