PHP数组排序,强制第一行

如何在 PHP 中对数组进行排序以强制将所选行作为第一行?


我的阵列是


array[]=array(id=>'a', content=>'lemon');

array[]=array(id=>'b', content=>'apple');

array[]=array(id=>'c', content=>'banana');

array[]=array(id=>'d', content=>'cherry');

如何对数组进行排序以强制


array[]=array(id=>'b', content=>'apple');

作为第一行,其余无关紧要(苹果是关键)。


在其他示例中,将排序以获取


array[]=array(id=>'d', content=>'cherry');

作为第一行,其余无关紧要(樱桃是关键)。


泛舟湖上清波郎朗
浏览 210回答 3
3回答

手掌心

另一种方法是使用 有效地旋转数组array_slice,将您想要的元素带到开始处:$first = 'apple';$k = array_search($first, array_column($array, 'content'));$array = array_merge(array_slice($array, $k), array_slice($array, 0, $k));print_r($array);输出:Array (  [0] => Array ( [id] => b [content] => apple )  [1] => Array ( [id] => c [content] => banana )  [2] => Array ( [id] => d [content] => cherry )  [3] => Array ( [id] => a [content] => lemon ) )

皈依舞

有两种方法我可以想到这样做。第一个是评论中的 Ultimater 建议提取匹配的行,然后排序,然后将行添加回...$first = 'apple';$array = [];$array[]=array('id'=>'a', 'content'=>'lemon');$array[]=array('id'=>'b', 'content'=>'apple');$array[]=array('id'=>'c', 'content'=>'banana');$array[]=array('id'=>'d', 'content'=>'chery');$firstElement = array_search($first, array_column($array, "content"));$row = $array[$firstElement];unset($array[$firstElement]);sort($array);array_unshift($array, $row);print_r($array);第二个是使用usort和添加特定的子句,如果键首先匹配你想要的行,那么它总是会强制它到第一行......$first = 'apple';usort($array, function ($a, $b) use ($first){&nbsp; &nbsp; if ( $a['content'] == $first)&nbsp; &nbsp;{&nbsp; &nbsp; &nbsp; &nbsp; return -1;&nbsp; &nbsp; }&nbsp; &nbsp; if ( $b['content'] == $first)&nbsp; &nbsp;{&nbsp; &nbsp; &nbsp; &nbsp; return 1;&nbsp; &nbsp; }&nbsp; &nbsp; return $a <=> $b;});print_r($array);(我已经使用<=>了 PHP 7+,如果您需要使用 PHP 5,还有其他选择)。如果您的评论表明不需要对其余数据进行排序,那么应该使用第一组代码减去sort()。

潇湘沐

另一种选择 - 如果 id:content 是一对一的,我们可以按内容索引数组,并与具有单个空“apple”键(或您要查找的任何内容值)的数组合并。$array&nbsp;=&nbsp;array_merge(['apple'&nbsp;=>&nbsp;[]],&nbsp;array_column($array,&nbsp;null,&nbsp;'content'));如果生成的字符串键不受欢迎,则可以使用 重新索引数组array_values。如果数组只包含 id 和 content 并且 id:content 实际上是一对一的,则键值对的“字典”将比这样的行列表更容易处理,最好设置如果可能的话,以这种方式开始。如果 id:content 不是一对一的,那么...没关系。;-)
打开App,查看更多内容
随时随地看视频慕课网APP