Reputation: 45002
I have the following array:
Array
(
[Places] => Array
(
[public] => 0
[entities] => Array
(
...
)
)
[Issues] => Array
(
[public] => 1
[entities] => Array
(
...
)
)
[Source] => Array
(
[public] => 0
[entities] => Array
(
...
)
)
)
I would like to be able to sort by the array by the public key. I know I may have to use either ksort
or usort
but I am unsure on how to implement this.
Any ideas would be great thanks!
Upvotes: 3
Views: 1155
Reputation: 1988
Try this:
$code = "return (-1*strnatcmp(\$a['public'], \$b['public']));";
uasort($array, create_function('$a,$b', $code));
Upvotes: 0
Reputation: 91430
You could use usort with callback function.
function cmp($a, $b) {
return $a['public'] == $b['public'] ? 0 : $a['public'] > $b['public'] ? 1 : -1;
}
usort($array, "cmp");
Upvotes: 0
Reputation: 10534
The general way to do this using array_multisort
is to place your sorting value into its own array and then sort both arrays using that as the primary sorting array.
Try the following:
$test = array(
'Places' => array(
'public' => 0,
'entities' => array(
)
),
'Issues' => array(
'public' => 1,
'entities' => array()
),
'Source' => array(
'public' => 0,
'entities' => array()
)
);
echo '<pre>';
print_r($test);
echo '</pre>';
$sort = array();
foreach ($test as $k => $a) {
$sort[$k] = $a['public'];
}
// placing $sort first in array_multisort causes $test to be sorted in same order as the values in $sort
array_multisort($sort,SORT_ASC,$test);
echo '<pre>';
print_r($test);
echo '</pre>';
Upvotes: 0
Reputation: 3703
Here's an interesting link: http://www.the-art-of-web.com/php/sortarray/
I would try a
usort(usort(array, function), function);
I can try a sample code upon request, but the information is already there for the taking.
Upvotes: 1
Reputation: 1751
take a look at this, using array_multisort :
$test = array(
'Places' => array(
'public' => 0,
'entities' => array(
)
),
'Issues' => array(
'public' => 1,
'entities' => array()
),
'Source' => array(
'public' => 0,
'entities' => array()
)
);
echo '<pre>';
print_r($test);
echo '</pre>';
array_multisort($test,SORT_ASC,$test);
echo '<pre>';
print_r($test);
echo '</pre>';
Upvotes: 0
Reputation: 97835
usort($array, function ($a, $b) { return $a["public"] - $b["public"]; });
Upvotes: 4