Domanda

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')
    );
È stato utile?

Soluzione

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];
}

Altri suggerimenti

$result = array();

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

var_dump($result);
Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top