1

Similar to the question: Sort an Array by keys based on another Array? only I want to drop any keys that arent in common.

Essentially I tried filtering the variables by the keys via array_intersect_key($VARIABLES, array_flip($signature_args)); and then tried to sort it with array_merge(array_flip($signature_args), $filtered)

Shown here:

$VARIABLES = array('3'=>'4', '4'=>'5', '1'=>'2');
$signature_args = array('1', '2', '3');

$filtered = array_intersect_key($VARIABLES, array_flip($signature_args));
var_dump($filtered);

var_dump(array_merge(array_flip($signature_args), $filtered));

produces:

array(2) {
  [3]=>
  string(1) "4"
  [1]=>
  string(1) "2"
}
array(5) {
  [0]=>
  int(0)
  [1]=>
  int(1)
  [2]=>
  int(2)
  [3]=>
  string(1) "4"
  [4]=>
  string(1) "2"
}

and not the

array(2) {
  [3]=>
  string(1) "4"
  [1]=>
  string(1) "2"
}
array(2) {
  [1]=>
  string(1) "2"
  [3]=>
  string(1) "4"
}

that I expected, why?

Community
  • 1
  • 1
chacham15
  • 13,719
  • 26
  • 104
  • 207

2 Answers2

1

This should work for you:

<?php

    $VARIABLES = array('3'=>'4', '4'=>'5', '1'=>'2');
    $signature_args = array('2', '3', '1');

    $filtered = array_intersect_key($VARIABLES, array_flip($signature_args));
    var_dump($filtered);

    $ordered = array();
    foreach ($signature_args as $key) {
        if(!empty($filtered[$key]))
        $ordered[$key] = $filtered[$key] ;
    }

    var_dump($ordered);

?>

Or if you want you can use this:

array_walk($signature_args, function($key) { 
    if(!empty($filtered[$key])) $ordered[$key] = $filtered[$key] ;
}, $ordered); 
chacham15
  • 13,719
  • 26
  • 104
  • 207
Rizier123
  • 58,877
  • 16
  • 101
  • 156
  • hmm, I just did a small fix, but if we're going to use our own loop, to create the result array, then theres no point in generating the `$filtered` variable, we can take the value directly from `$VARIABLES`. i.e. `$ordered[$key] = $VARIABLES[$key];` – chacham15 Jan 06 '15 at 01:29
0

To use the "allowed" array not only to filter the input array but also to order the output, filter both arrays by each other, then replace (or merge) the input array into the allowed array.

Code: (Demo)

$input = ['3' => '4', '4' => '5', '1' => '2'];
$allowed = ['1', '2', '3'];

$flipAllowed = array_flip($allowed);

var_export(
    array_replace(
        array_intersect_key($flipAllowed, $input), // filtered allowed
        array_intersect_key($input, $flipAllowed) // filtered input
    )
);

Output:

array (
  1 => '2',
  3 => '4',
)
mickmackusa
  • 43,625
  • 12
  • 83
  • 136