chacham15
chacham15

Reputation: 14251

Intersect and Sort an Array by keys based on another Array?

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?

Upvotes: 1

Views: 104

Answers (2)

mickmackusa
mickmackusa

Reputation: 47992

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',
)

Upvotes: 0

Rizier123
Rizier123

Reputation: 59701

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); 

Upvotes: 1

Related Questions