Alphabetize a multidimensional array

How can I get this multidimensional array to print in alphabetical order?

<?php
$foodArray1 = Array();
$foodArray1 = array(

0=> array('name' => 'Zucchini', 'description' => 'A delicious healthy vegetable', 'image' => 'zucchini.gif'),
1=> array('name' => 'Apple', 'description' => 'One of these a day keeps the doctor away!', 'image' => 'apple.gif'),
2=> array('name' => 'Pizza', 'description' => 'Isnt it weird that pizza is round, but is cut into triangles and comes in a square box?', 'image' => 'pizza.gif')
);
	
uksort($foodArray1[1]['name'], 'strnatcasecmp');
		
$id  = 0;

foreach($foodArray1 as $key => $value){
	
	$row = $foodArray1[$id];
	echo '<img src="/images/'.$row['image'].'" /><br>';
    echo $row['name'].' - '.$row['description']; 
    echo '<br><br>';
	
    $id++;
}
?>

http://php.net/array-multisort but if the data come from a database, use ORBER BY in the query.

1 Like

I tried this but no luck

<?php
$foodArray1 = Array();
$foodArray1 = array(

0=> array('name' => 'Zucchini',					       'description' => 'A delicious healthy vegetable', 'image' => 'zucchini.gif'),
1=> array('name' => 'Apple',					       'description' => 'One of these a day keeps the doctor away!', 'image' => 'apple.gif'),
2=> array('name' => 'Pizza',					       'description' => 'Isnt it weird that pizza is round, but is cut into triangles and comes in a square box?', 'image' => 'pizza.gif')
);

array_multisort($foodArray1, SORT_ASC, SORT_STRING);
                		
$id  = 0;

foreach($foodArray1 as $key => $value){
	
	$row = $foodArray1[$id];
	echo '<img src="/images/'.$row['image'].'" /><br>';
    echo $row['name'].' - '.$row['description']; 
    echo '<br><br>';
	
    $id++;
}
?>

Using array_multisort here might be possible with some tricks, but it’s actually more for sorting multiple arrays (or array-dimensions) at once… so I think in this case, it would be much easier to use usort instead:

usort($foodArray1, function ($a, $b) {
    return $a['name'] > $b['name'];
});
1 Like
$foodArray1 = array(

    0=> array('name' => 'Zucchini', 'description' => 'A delicious healthy vegetable', 'image' => 'zucchini.gif'),
    1=> array('name' => 'Apple', 'description' => 'One of these a day keeps the doctor away!', 'image' => 'apple.gif'),
    2=> array('name' => 'Pizza', 'description' => 'Isnt it weird that pizza is round, but is cut into triangles and comes in a square box?', 'image' => 'pizza.gif')
);

usort($foodArray1,function($a1,$a2) {
    return strnatcasecmp($a1['name'],$a2['name']);
});
foreach($foodArray1 as $food) {
    echo $food['name'] . "\n";
}

OOPS: @m3g4p0p beat me to it. Though his return statement is not quite right.

2 Likes

Thank you both! usort did it… this will save me so much time and headache… thank you!

This topic was automatically closed 91 days after the last reply. New replies are no longer allowed.