Question

Is it possible to sort multidimensional array keys by searched terms? For example, i have something like this:

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

Now if i pass the keyword term 'search' in the url, how can i return the array so that all the keys that contain the word 'search' are rendered on top?

It needs to come back like:

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
        )

)
Was it helpful?

Solution

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

Output:

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
        )

)
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top