PHP:如何基于搜索的术语对多维数组进行排序

时间:2013-12-31 14:08:49

标签: php arrays sorting alfresco cmis

是否可以按搜索条件对多维数组键进行排序?例如,我有这样的事情:

 $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);

现在如果我在网址中传递关键词“搜索”,我该怎样才能返回数组,以便所有包含“搜索”一词的键都呈现在顶部?

需要回来:

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
        )

)

1 个答案:

答案 0 :(得分:0)

<?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
        )

)