Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
870 views
in Technique[技术] by (71.8m points)

php - Sort multidimensional array based on another array

I have one array ($sort) that looks like:

  [1]=>16701

  [2]=>16861

  [3]=>16706

And an array ($images), which looks like:

  [0]=>
  array(4) {
    ["href"]=> string(35) "mystring"
    ["url"]=>  string(67) "mystring2"
    ["didascalia"]=> string(29) "mystring3"
    ["id"]=> 16861
  }
  [1]=>
  array(4) {
    ["href"]=> string(35) "mystring"
    ["url"]=>  string(70) "mystring2"
    ["didascalia"]=> string(37) "mystring3"
    ["id"]=> 16706
  }
  [2]=>
  array(4) {
    ["href"]=> string(35) "mystring"
    ["url"]=>  string(66) "mystring2"
    ["didascalia"]=> string(24) "mystring3"
    ["id"]=> 16701
  }

I need to sort $images, based on value "id", using $sort. So my result should be

[0]=>
array(4) {
  ["href"]=> string(35) "mystring"
  ["url"]=>  string(66) "mystring2"
  ["didascalia"]=> string(24) "mystring3"
  ["id"]=> 16701
}

[1]=>
array(4) {
  ["href"]=> string(35) "mystring"
  ["url"]=>  string(67) "mystring2"
  ["didascalia"]=> string(29) "mystring3"
  ["id"]=> 16861
}

[2]=>
array(4) {
  ["href"]=> string(35) "mystring"
  ["url"]=>  string(70) "mystring2"
  ["didascalia"]=> string(37) "mystring3"
  ["id"]=> 16706
}

How can I do it? I tried using multisort, array_map but without success.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Since you already have the ids in the desired sort order, the only barrier to sorting $images efficiently is the inability to immediately fetch an image given its id. So let's fix that by reindexing $images to use the id as the array key using array_column (don't get thrown by the name, it can also be used for reindexing):

// array_column is only available in PHP 5.5+
$images = array_column($images, null, 'id');

After this it's trivial to get a sorted array:

$sortedImages = [];
foreach ($sort as $id) {
    $sortedImages[] = $images[$id];
}

For PHP < 5.5 you can substitute the array_column reindexing with this:

$imageIds = array_map(function($i) { return $i['id']; }, $images);
$images = array_combine($imageIds, $images);

Alternatively you can get an implementation written in PHP by the author of array_column himself.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...