Как отсортировать Object Array Collection по значению в PHP - PullRequest
0 голосов
/ 17 декабря 2018

Итак, у меня есть этот результат из базы данных:

object(Illuminate\Support\Collection)#538 (1) {
  ["items":protected]=>
    array(3) {
        [0]=>
        object(stdClass)#536 (3) {
           ["col_header"]=>
           string(7) "other_1"
           ["col_order"]=>
           int(12)
           ["data"]=>
           string(13) "asdgasdgfasdg"
        }
        [1]=>
        object(stdClass)#545 (3) {
           ["col_header"]=>
           string(7) "other_2"
           ["col_order"]=>
           int(10)
           ["data"]=>
           string(10) "dfhgsdhgsd"
       }
       [2]=>
       object(stdClass)#533 (3) {
           ["col_header"]=>
           string(7) "other_3"
           ["col_order"]=>
           int(11)
           ["data"]=>
           string(1) "s"
       }
}

Теперь, как мне отсортировать его результат на основе значения col_order? Результат должен быть таким:

object(Illuminate\Support\Collection)#538 (1) {
  ["items":protected]=>
    array(3) {
        [0]=>
        object(stdClass)#545 (3) {
           ["col_header"]=>
           string(7) "other_2"
           ["col_order"]=>
           int(10)
           ["data"]=>
           string(10) "dfhgsdhgsd"
        }
        [1]=>
        object(stdClass)#533 (3) {
           ["col_header"]=>
           string(7) "other_3"
           ["col_order"]=>
           int(11)
           ["data"]=>
           string(1) "s"
        }
        [2]=>
        object(stdClass)#536 (3) {
           ["col_header"]=>
           string(7) "other_1"
           ["col_order"]=>
           int(12)
           ["data"]=>
           string(13) "asdgasdgfasdg"
        }
}

Я попытался использовать asort() здесь, но кажется, что он поддерживает только ассоциативный массив.Есть ли способ, которым я могу разобраться с этим?

Ответы [ 2 ]

0 голосов
/ 17 декабря 2018

Вы можете использовать usort()

$test = array(array("col_header" => "other_1",
                    "col_order" => 12,
                    "data" => "asdgasdgfasdg"),
              array("col_header" => "other_2",
                    "col_order" => 10,
                    "data" => "dfhgsdhgsd"),
              array("col_header" => "other_3",
                    "col_order" => 11,
                    "data" => "s"));

usort($test, function($a, $b)
             {
                 if ($a["col_order"] == $b["col_order"])
                     return (0);
                 return (($a["col_order"] < $b["col_order"]) ? -1 : 1);
             });

var_dump($test);

Вывод:

array (size=3)
  0 => 
    array (size=3)
      'col_header' => string 'other_2' (length=7)
      'col_order' => int 10
      'data' => string 'dfhgsdhgsd' (length=10)
  1 => 
    array (size=3)
      'col_header' => string 'other_3' (length=7)
      'col_order' => int 11
      'data' => string 's' (length=1)
  2 => 
    array (size=3)
      'col_header' => string 'other_1' (length=7)
      'col_order' => int 12
      'data' => string 'asdgasdgfasdg' (length=13)

Но я предлагаю вам отсортировать результатынепосредственно из запроса SQL:

SELECT *
FROM yourTable
...
ORDER BY col_order ASC
0 голосов
/ 17 декабря 2018

Ответ: http://php.net/manual/en/function.usort.php - сортировка выполняется с помощью пользовательской функции сравнения.Замените a на col_order в следующем фрагменте:

<?php

$class1 = new stdClass();
$class1->a = 1;
$class2 = new stdClass();
$class2->a = 2;
$class3 = new stdClass();
$class3->a = 3;

$input = [$class3,$class2,$class1];

var_dump($input);

usort($input, function($a, $b) {
      if ($a->a == $b->a) {
        return 0;
    }
    return ($a->a < $b->a) ? -1 : 1;
});

var_dump($input);

https://3v4l.org/9ELKp

Поскольку вы используете Illuminate, вы можете вместо этого захотеть взглянуть и на https://laravel.com/api/5.5/Illuminate/Database/Query/Builder.html#method_orderByи используйте его вместо этого.

Редактируйте из комментариев: используя PHP 7+, вы можете использовать оператор космического корабля, чтобы упростить функцию сравнения:

usort($input, function($a, $b) {
    return $a->a <=> $b->a;
});
...