I try pretty much everything, read trough whole php.net and I can't seem to find a way how to get array of all keys that have the same value.
For example this is array:
Array
(
[869] => 87
[938] => 89
[870] => 127
[871] => 127
[940] => 127
[942] => 123
[947] => 123
[949] => 75
)
Array we want in my case is:
Array
(
[1] => array
(
[1] => 870
[2] => 871
[3] => 940
)
[2] => array
(
[1] => 942
[2] => 947
)
)
Here is a function that will do what you want. Many not be the simplest it could be but it works:
<?php
$myArray = array(
869 => 87,
938 => 89,
870 => 127,
871 => 127,
940 => 127,
942 => 123,
947 => 123,
949 => 75
);
$newArray = $foundKeys = array();
$itt = 0;
foreach($myArray as $i => $x){
foreach($myArray as $j => $y ){
if($i != $j && !in_array($i,$foundKeys) && $x == $y){
if(!is_array($newArray[$itt])){
$newArray[$itt] = array($i);
}
array_push($newArray[$itt],$j);
array_push($foundKeys,$j);
}
}
$itt++;
}
print_r($newArray);
results in:
Array
(
[2] => Array
(
[0] => 870
[1] => 871
[2] => 940
)
[5] => Array
(
[0] => 942
[1] => 947
)
)
It would be easier to do if your second array had the value you're checking for as it's key e.g.
Array
(
[127] => array
(
[1] => 870
[2] => 871
[3] => 940
)
[123] => array
(
[1] => 942
[2] => 947
)
)
Then you could do something like this:
<?php
$output = array();
foreach($your_array as $key => $current) {
if( !array_key_exists($current, $output) ) {
// create new entry
$output[$current] = array( $key );
} else {
// add to existing entry
$output[$current][] = $key;
}
}
print_r($output);
?>
This should return the output above...
My short code.
$array =Array
(
869 => 87,
938 => 89,
870 => 127,
871 => 127,
940 => 127,
942 => 123,
947 => 123,
949 => 75
);
$return = array();
foreach ($array as $key => $value)
$return[$value][] = $key;
var_dump(array_values($return));