PHP - remove siblings (sheets) that are the same from an array (remove same arrays from an array)
Trying to remove same siblings / same arrays from a nested array.
eg
$data = [
'test' => [
'a' => [
'b' => 'something',
5 => [
'a' => [
1 => 'test1',
19 => 'test2',
6 => 'test3',
],
0 => 'test',
],
],
'b' => 1,
2 => [
3 => 'something',
5 => 'somethingelse',
],
4 => 'body'
],
'anothertest' => [
'b' => 1,
0 => [
'test' => 1,
2 => 'something',
3 => 'somethingelse',
],
1 => [
'test' => 1,
2 => 'something',
3 => 'somethingelse',
],
],
];
Array
(
[test] => Array
(
[a] => Array
(
[b] => something
[5] => Array
(
[a] => Array
(
[1] => test1
[19] => test2
[6] => test3
)
[0] => test
)
)
[b] => 1
[2] => Array
(
[3] => something
[5] => somethingelse
)
[4] => body
)
[anothertest] => Array
(
[b] => 1
[0] => Array
(
[test] => 1
[2] => something
[3] => somethingelse
)
[1] => Array
(
[test] => 1
[2] => something
[3] => somethingelse
)
)
)
$ data ['anothertest'] [0] and $ data ['anothertest'] [1] are the same, so you need to delete.
Arrays with string indices can be skipped.
Found how to compare one array to another in the foreach key values ββblock.
I know I can compare the same array to an operator ===
, but I donβt know how I can access the next one in a foreach loop.
Here is my code with a PSUEDOCODE block, which I don't know how to do.
function cleansiblings($array)
{
foreach ($array as $key => $value) {
if (!is_string($key)) {
//PSEUDO CODE
//compare current $value to $value+1??
}
}
}
Any help is appreciated.
Thank,
source to share
You can remove duplicates from a multidimensional array like
<?php
function get_unique($array){
$result = array_map("unserialize", array_unique(array_map("serialize", $array)));
foreach ($result as $key => $value){
if ( is_array($value) ){
$result[$key] = get_unique($value);
}
}
return $result;
}
echo "<pre/>";print_r(get_unique($data));
?>
Output: - https://eval.in/817099
source to share
To answer just the last part of your question, you can access the original $ array in a foreach loop using the $ key:
function cleansiblings($array)
{
foreach ($array as $key => $value) {
if (!is_string($key)) {
if (isset($array[$key+1])) {
// Compare $array[$key] (or $value, it is the same) with $array[$key+1]
// To remove item from array, just unset it: unset($array[$key]).
// Note that you can alter iterated array in PHP,
// but not in some other languages.
}
}
}
}
source to share