Reputation: 3481
$name = [
['Jane Smith'],
['John Paul'],
['Jennifer'],
['Paolo'],
['Delilah'],
];
Is it possible to alphabetically arrange this array?
How can I use the sort()
in here?
Upvotes: 3
Views: 232
Reputation: 9874
Since it looks like you're trying to sort an array of arrays of strings instead of an array of strings, you cannot use sort()
.
$array = array(array('Jane Smith'), array('John Paul'), array('Jennifer'));
function cmp($a, $b)
{
$a = $a[0];
$b = $b[0];
if ($a == $b) {
return 0;
}
return ($a < $b) ? -1 : 1;
}
usort($array, "cmp");
foreach($name as $a){
print_r($a);
}
Example code based on this documentation.
Upvotes: 0
Reputation: 818
Take a look at here for all kinds of PHP array sorting. But for your specific question after doing array_merge()
on all you arrays to have a single onw, either sort()
or asort()
should work just like this:
$all=array();
foreach($name as $a){
$all=array_merge($all, $a);
}
sort($all);
print_r($all);
OR
$all=array();
foreach($name as $a){
$all=array_merge($all, $a);
}
asort($a);
print_r($a);
Upvotes: -1
Reputation: 32710
Try this :
$array = your array
$result = call_user_func_array('array_merge', $array);
sort($result);
echo "<pre>";
print_r($result);
Upvotes: 4
Reputation: 4282
Try this:
<?php
$ar1 = array("Jane Smith", "John Paul ", "Jennifer", "Paolo","Delilah");
function alphasort($a, $b) {
if ($a['name'] == $b['name']) {
return 0;
}
return ($a['name'] < $b['name']) ? -1 : 1;
}
usort ($ar1,'alphasort');
echo '<pre>';
print_r($ar1);
?>
Result:
Array
(
[0] => Delilah
[1] => Jane Smith
[2] => Jennifer
[3] => John Paul
[4] => Paolo
)
Upvotes: 2