I need your help. I'm looking for a smart way to find out if my array of objects within an object has multiple name values or not to do a validation since it's only allowed to have one array name per inner array:
$elements = [];
$elements[18][20] = [
[
'name' => 'Color',
'value' => 'Red'
],
[
'name' => 'Color',
'value' => 'Green'
],
[
'name' => 'Size',
'value' => 'S'
]
];
$elements[18][21] = [
[
'name' => 'Size',
'value' => 'S'
],
[
'name' => 'Length',
'value' => '20'
],
];
error_log( print_r( $elements, true ) );
So the object 20 for example is invalid because it has 2 colors with the same value. At the end I was hoping to get a result array containing 1 duplicate name. This way I can output them like: "You have at least one duplicate name: Color".
My first idea was to loop over the array and do a second loop. This way it was possible to receive the inner arrays containing the stuff. Now I was able to add every name to another array. After this I was able to use count()
and array_intersect()
to receive a value of x which showed me if there are duplicates or not.
Now I had a count, but not the actual value to display. Before I use a semi-good solution, I was hoping to get any ideas here how I can make it better!
CodePudding user response:
This loop will generate your expected output:
foreach($elements[18] as $index => $element){
//Get all the elements' names
$column_key = array_column($element, 'name');
//Get the count of all keys in the array
$counted_values = array_count_values($column_key);
//Check if count is > 1
$filtered_array = array_filter($counted_values, fn($i) => $i > 1);
//If the filter is not empty, show the error
if(!empty($filtered_array)){
//get the key name
$repeated_key = array_key_first($filtered_array);
echo "You have at least one duplicate name: {$repeated_key} at index {$index}";
break;
}
}
It relies in the array_count_values function.