Flip Associative Array and Store New Values in Subarrays to Prevent Losing Duplicated Values

Flip associative array and store new values in subarrays to prevent losing duplicated values

$grouped = array();
foreach ($input as $choice => $group) {
$grouped[$group][] = $choice;
}

var_dump($grouped);

Missing values from the same key after using array_flip function

You will have to loop it yourself and build a new array:

$files = array(
"Input.txt" => "Randy",
"Code.py" => "Stan",
"Output.txt" => "Randy"
);

$new_files = array();

foreach($files as $k=>$v)
{
$new_files[$v][] = $k;
}

print_r($new_files);

Function to Flip Array Values to Array Keys?

$arr = array ( 1 => '0', 6 => '1', 7 => '1', 8 => '7' );

// Find unique values of array and make them as keys
$res = array_flip($arr);
// Find keys from sourse array with value of key in new array
foreach($res as $k =>$v) $res[$k] = implode(", ", array_keys($arr, $k));

result

Array
(
[0] => 1
[1] => 6, 7
[7] => 8
)

Within a foreach() expression, is the value defined before or after the key?

A foreach() always assigns the value variable before assigning the key variable. (Demo)

This seems a little counterintuitive because $v visually appears to be declared after it is access by key declaration.

This means you can safely use:

$array = ['a', 'b'];
$result = [];
foreach ($array as $result["prefix_$v"] => $v);
var_export($result);

to produce:

array (
'prefix_a' => 0,
'prefix_b' => 1,
)

The newly generated array has prefixed keys based on the original values and the original indexes become the new values.

Without the prefix_ prepended to the string, the action is effectively the same as array_flip().


Reversing the assignments so that the value variable receives the key does not work as intended. You might hope to generate ["prefix_0", "prefix_1"] but it does not and it also generates Notices/Warnings due to trying to access an undeclared variable. (The complaint is only on the first iteration because after the first iteration, $k is declared -- it is the previous iteration's key.)

$array = ['a', 'b'];
$result = [];
foreach ($array as $k => $result["prefix_$k"]);
// not defined on first iteration -------^^
var_export($result);

Bad Output:

Warning: Undefined variable $k in /in/iVm1u on line 6
array (
'prefix_' => 'a',
'prefix_0' => 'b',
)

For additional context, I'll offer one more working example that generates a multi-dimensional array using the value to determine the array keys in the output array. (Demo)

$array = [2, 3, 5];

$result = [];
foreach ($array as $result[$v * $v][$v] => $v);
var_export($result);

Output:

array (
4 =>
array (
2 => 0,
),
9 =>
array (
3 => 1,
),
25 =>
array (
5 => 2,
),
)

Get the keys for duplicate values in an array

function get_keys_for_duplicate_values($my_arr, $clean = false) {
if ($clean) {
return array_unique($my_arr);
}

$dups = $new_arr = array();
foreach ($my_arr as $key => $val) {
if (!isset($new_arr[$val])) {
$new_arr[$val] = $key;
} else {
if (isset($dups[$val])) {
$dups[$val][] = $key;
} else {
$dups[$val] = array($key);
// Comment out the previous line, and uncomment the following line to
// include the initial key in the dups array.
// $dups[$val] = array($new_arr[$val], $key);
}
}
}
return $dups;
}

obviously the function name is a bit long;)

Now $dups will contain a multidimensional array keyed by the duplicate value, containing each key that was a duplicate, and if you send "true" as your second argument it will return the original array without the duplicate values.

Alternately you could pass the original array as a reference and it would adjust it accordingly while returning your duplicate array

How to Flatten a Multidimensional Array?

You can use the Standard PHP Library (SPL) to "hide" the recursion.

$a = array(1,2,array(3,4, array(5,6,7), 8), 9);
$it = new RecursiveIteratorIterator(new RecursiveArrayIterator($a));
foreach($it as $v) {
echo $v, " ";
}

prints

1 2 3 4 5 6 7 8 9 


Related Topics



Leave a reply



Submit