Reputation: 5525
I have this array :
Array
(
[0] => Array
(
[id] => 83
[value] => Figures
)
[1] => Array
(
[id] => 85
[value] => Toys
)
[2] => Array
(
[id] => 36
[value] => Nintendo Switch
)
)
and I have this code to sort that array based on id
:
function cmp($a, $b) {
return strcmp($a->id, $b->id);
}
while ($row = $result->fetch_assoc()) {
$category = json_decode($row['product_cat'], true);
usort($category, "cmp");
echo '<pre>';
print_r($category);
echo '</pre>';
}
the result is not working as I expected, because id=85
placed before id=83
:
Array
(
[0] => Array
(
[id] => 36
[value] => Nintendo Switch
)
[1] => Array
(
[id] => 85
[value] => Toys
)
[2] => Array
(
[id] => 83
[value] => Figures
)
)
why PHP successfully placed the id=36
as first value of array, but failed to sort id=85
and id=83
thank you.
Upvotes: 0
Views: 75
Reputation: 1605
It is just a one liner
array_multisort( array_column($yourArray, "id"), SORT_ASC, $yourArray );
You can find it here as well: http://php.net/manual/en/function.array-multisort.php
search for "array_column" on that manual page.
I used this to test:
$yourArray = array (
"0" => Array
(
"id" => 83,
"value" => "Figures"
),
"1" => Array
(
"id" => 85,
"value" => "Toys"
),
"2" => Array
(
"id" => 36,
"value" => "Nintendo Switch"
)
);
array_multisort( array_column($yourArray, "id"), SORT_ASC, $yourArray );
print_r($yourArray);
And the result is this:
Array ( [0] => Array ( [id] => 36 [value] => Nintendo Switch )
[1] => Array ( [id] => 83 [value] => Figures )
[2] => Array ( [id] => 85 [value] => Toys ) )
Upvotes: 0
Reputation: 411
$category = array ([
'id' => 36,
'value' => 'Nintendo Switch'
], [
'id' => 85,
'value' => 'Toys'
], [
'id' => 83,
'value' => 'Figures'
]);
$sortArry = [];
foreach ($category as $c) {
$sortArry[$c['id']] = $c;
}
echo '<pre>';
print_r($sortArry);
array_multisort($sortArry);
print_r($sortArry);
exit;
Place id as key in your array and then use multisort. It will work.
Upvotes: 0
Reputation: 720
You can use like this
$mylist = array(array("id"=>83,"value"=>"Figures"),array("id"=>85,"value"=>"Toys"),array("id"=>36,"value"=>"Nintendo Switch"));
echo "<pre>";
$sort = array();
foreach($mylist as $k=>$v) {
$sort['id'][$k] = $v['id'];
$sort['value'][$k] = $v['value'];
}
# sort by event_type desc and then title asc
array_multisort($sort['id'], SORT_ASC, $sort['value'], SORT_ASC,$mylist);
print_r($mylist);
And get output like below
Array
(
[0] => Array
(
[id] => 36
[value] => Nintendo Switch
)
[1] => Array
(
[id] => 83
[value] => Figures
)
[2] => Array
(
[id] => 85
[value] => Toys
)
)
Upvotes: 1
Reputation: 1642
change
return strcmp($a->id, $b->id);
to
return strcmp($a['id'], $b['id']);
Upvotes: 2