I have the following JSON array, I would like to adjust the array to only keep unique name
values, meaning id could be across numerous objects, but name must be unique, overall Tim and Jacob can only be listed once.
$data = ' [ { "name": "Jacob", "id": 4 }, { "name": "Jacob", "id": 3 }, { "name": "Tim", "id": 2 }, { "name": "Brady", "id": 2 }, { "name": "Tim", "id": 1 } ]'; $array = json_decode($data, TRUE); $array = array_values( array_unique( $array, SORT_REGULAR ) ); $result = json_encode( $array );
The following is what I have currently tried, but it looks at both values in the object, so it leaves them as is.
Result I am looking for:
[ { "name": "Jacob", "id": 4 }, { "name": "Tim", "id": 2 }, { "name": "Brady", "id": 2 } ]
Advertisement
Answer
You can write a function which goes through each of the entries in the array and removes them if their name has been seen before.
function array_unique_names($array) { // Copy our input as a temporary new array $output = $array; // Keep track of which names we've seen before $seen_names = []; foreach ($output as $key => $value) { // If we've seen a name before, remove it from our output if (in_array($value['name'], $seen_names)) { unset($output[$key]); } // Otherwise, keep it but add it to the list of seen names else { $seen_names[] = $value['name']; } } // Return a re-indexed array return array_values($output); } $data = // Your JSON input string $array = json_decode($data, TRUE); $array = array_unique_names($array); $result = json_encode($array);