1

I want to sort an array so that a specific array with a specific value is shown as the first in the array.

The array I have:

array = [
        [0] => [
            'id' => 123,
            'name' => 'Random'
        ],
        [1] => [
            'id' => 156,
            'name' => 'keyboard'
        ],
        [2] => [
            'id' => 12235,
            'name' => 'Text'
        ],
    ];

I want the sub-array where the name is 'keyboard' to be the first in line of the big array.

Does anyone have suggestions?

  • Possible duplicate of [Sort multi-dimensional array by specific key](https://stackoverflow.com/questions/4022289/sort-multi-dimensional-array-by-specific-key) – Patrick Q Mar 06 '18 at 15:43

2 Answers2

2

usort Sort an array by values using a user-defined comparison function

$array = [
    0 => [
        'id' => 123,
        'name' => 'Random'
    ],
    1 => [
        'id' => 156,
        'name' => 'keyboard'
    ],
    2 => [
        'id' => 12235,
        'name' => 'Text'
    ],
];

usort($array, function ($item) {
    return  $item['name'] != 'keyboard';
});

print_r($array);

See the demo

Song
  • 301
  • 1
  • 2
-1
$myArray = [
    [0] => [
        'id' => 123,
        'name' => 'Random'
    ],
    [1] => [
        'id' => 156,
        'name' => 'keyboard'
    ],
    [2] => [
        'id' => 12235,
        'name' => 'Text'
    ],
];

$temp = $myArray[0];
$myArray[0] = $myArray[1];
$myArray[1] = $temp;
MackProgramsAlot
  • 583
  • 1
  • 3
  • 16