0

I have an array A with these value

array(
  0 => 'D003',
  1 => 'P001',
  2 => 'P002',
  3 => 'D001'
);

and I have another multidimensional array B with these values

 array(
      0 => 
        array(
          'waypoint_id' => 'D001',
          'count' => '5'),
      1 => 
        array(
          'waypoint_id' => 'D003',
          'count' => '1'),
      2 => 
        array(
          'waypoint_id' => 'P001',
          'count' => '2'),
      3 => 
        array(
          'waypoint_id' => 'P002',
          'count' => '1')
    );   

how to use array_multisort so that I can get my array B to be like these (same order as array B)

  array(
      0 => 
        array(
          'waypoint_id' => 'D003',
          'count' => '1'),
      1 => 
        array(
          'waypoint_id' => 'P001',
          'count' => '2'),
      2 => 
        array(
          'waypoint_id' => 'P002',
          'count' => '1'),
      3 => 
        array(
          'waypoint_id' => 'D001',
          'count' => '5')
    );

2 Answers 2

2

I'm not sure array_multisort() can help you here, as the contents of A aren't in any obvious order.

I'd do it by indexing B by waypoint purely for efficiency, and then creating a new $ordered array from A:

$indexed = array();
foreach($b as $array) {
    $indexed[$array['waypoint_id']] = $array;
}

$ordered = array();
foreach($a as $waypoint) {
    $ordered[] = $indexed[$waypoint];
}
Sign up to request clarification or add additional context in comments.

2 Comments

yeah this works. i thought array_multisort can be used to solve this. many thanks
I like this approach. +1
0
$result = array();

foreach ($A as $search) {
    foreach ($B as $elt) {
        if ($elt['waypoint_id'] === $search) {
            array_push($result, $B);
            break;
        }
    }
}

var_dump($result);

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.