PHP:如何根据搜索的词对多维数组进行排序



是否可以按搜索词对多维数组键进行排序?例如,我有这样的东西:

 $list =   array(
      'search' => array(
        'name' => 'Jon'),
      'search else' => array(
        'name' => 'Matt'),
      'not this' => array(
        'name' => 'Dan'),
      'neither this' => array(
        'name' => 'Oz'),
      'always search me' => array(
        'name' => 'Lukas')
    );
function sort_by_search($x, $y) {
  $term = $_GET['keyword'];
    return $x[$term] == $y[$term];
}
uasort($list, 'sort_by_search');
print_r($list);

现在,如果我在 url 中传递关键字术语"search",我如何返回数组,以便所有包含单词"search"的键都呈现在顶部?

它需要像这样返回:

Array
(
    [search] => Array
        (
            [name] => Jon
        )
    [search else] => Array
        (
            [name] => Matt
        )
    [always search me] => Array
        (
            [name] => Lukas
        )
    [not this] => Array
        (
            [name] => Dan
        )
    [neither this] => Array
        (
            [name] => Oz
        )
)
<?php
 $list =   array(
      'search' => array(
        'name' => 'Jon'),
      'search else' => array(
        'name' => 'Matt'),
      'not this' => array(
        'name' => 'Dan'),
      'neither this' => array(
        'name' => 'Oz'),
      'always search me' => array(
        'name' => 'Lukas')
    );
function key_compare($a, $b)
{
    $test_a = stripos($a, 'search');
    $result_a = (false===$test_a)?1:0;
    $test_b = stripos($b, 'search');
    $result_b = (false===$test_b)?1:0;
    return $result_a-$result_b;
}
uksort($list, 'key_compare');
echo '<pre>';
print_r($list);

输出:

Array
(
    [search] => Array
        (
            [name] => Jon
        )
    [search else] => Array
        (
            [name] => Matt
        )
    [always search me] => Array
        (
            [name] => Lukas
        )
    [not this] => Array
        (
            [name] => Dan
        )
    [neither this] => Array
        (
            [name] => Oz
        )
)

相关内容

  • 没有找到相关文章

最新更新