0

私は2つの配列を持っています.どちらも同じ数の要素と同じ値を持つ多次元であり、それらは異なる位置にあります(これらの値は実際にはデータベースからのIDであるため、1つのIDは1回だけ表示されます). 最初の配列にある値で2番目の配列をソートするにはどうすればよいですか?

たとえば、最初の配列が次のようになっている場合:

$array1[0][0] = 1;
$array1[0][x] = it doesn't matter what's here
$array1[1][0] = 4;
$array1[1][x] = it doesn't matter what's here
$array1[2][0] = 3;
$array1[2][x] = it doesn't matter what's here
...

2 番目の配列を並べ替えて、インデックス [0][0]、[1][0]、[2][0] などで array1 と同じ値になるようにする方法。

問題を解決する方法は次のとおりです。

$i=0
while ($i < (count($array1)-2)){ // * check down

  $find_id = $array1[$i][0];

  // here I need to search for index of that ID in other array
  $position = give_index($find_id, $array2);

  // swapping positions
  $temp = array2[$i][0];
  $array2[$i][0] = $array2[$position][0];
  $array2[$position][0] = $temp;

  // increasing counter
  i++;
}

function give_index($needle, $haystack){
  for ($j = 0, $l = count($haystack); $j < $l; ++$j) {
        if (in_array($needle, $haystack[$j][0])) return $j;
  }
  return false;
}
  • *インデックスは 0 から始まり、最後の要素は while ループの最後の反復によって自動的にソートされるため、チェックする必要がないため、-2 しかありません。

これは非常に単純な問題だと思うので、この解決策は良くないと思います(おそらく正しくないかもしれません)。私が見逃している PHP の簡単な方法はありますか?

4

2 に答える 2

0

usort ( http://php.net/manual/en/function.usort.php ) を調べます。

ユーザー提供の比較関数を使用して配列をソートする簡単な方法を提供します。

于 2013-03-08T00:59:00.963 に答える