Close

Code Snippets

How to Sort Multidimensional Arrays Using PHP

In this video, you’ll learn how to sort multidimensional arrays in PHP. You’ll not only learn basic sorting using array_multisort(), but you’ll also see a more advanced custom function for sorting multidimensional arrays by a specific key.

Multidimensional arrays can be one of the more confusing parts about learning PHP, but this video will help you get your head around it and give you some tools for sorting your multidimensional arrays that are simple and straight-forward.

<?php
$arr = array(
array('name' => 'John', 'age' => 30, 'website' => 'http://learnphp.co'),
array('name' => 'Joe', 'age' => 28, 'website' => 'http://johnmorrisonline.com'),
array('name' => 'Amy', 'age' => 32, 'website' => 'http://amy.com'),
array('name' => 'Alex', 'age' => 22, 'website' => 'http://thealex.com'),
array('name' => 'Pat', 'age' => 40, 'website' => 'http://patsjourney.com'),
);

?>

<pre><?php print_r($arr); ?></pre>

<?php
array_multisort($arr);
?>

<pre><?php print_r($arr); ?></pre>

<?php
function val_sort($array,$key) {

//Loop through and get the values of our specified key
foreach($array as $k=>$v) {
$b[] = strtolower($v[$key]);
}

print_r($b);

asort($b);

echo '<br />';
print_r($b);

foreach($b as $k=>$v) {
$c[] = $array[$k];
}

return $c;
}

$sorted = val_sort($arr, 'website');
?>

<pre><?php print_r($sorted); ?></pre>

December 29, 2011

How to Create an HTML Select Box From a MySQL Results Array Using PHP

This is a question I get quite a bit, so I figured I’d write a post on it:

How do I create an HTML select box with options from data in my database?

Here’s how:

The Query

First, let’s look at our query. Yours might look something like this:

<?php
$sql = "SELECT * FROM queried_table";
$query = mysql_query($sql);
while ( $results[] = mysql_fetch_object ( $query ) );
array_pop ( $results );
?>

That will select everything in our table and loop it into an array of objects containing the results. Now, we can take that array and create a HTML select box with it.

The HTML Select Box

Now, that we have our array of objects from our database we can use it to populate an HTML select box dynamically with PHP. Here’s how that might look:

<select name="the_name">
<?php foreach ( $results as $option ) : ?>
<option value="<?php echo $option->desired_value; ?>"><?php echo $option->desired_label; ?></option>
<?php endforeach; ?>
</select>

That’s it. The code above will loop through the array creating a new option for each element in the array… and populating each option with the desired values from your database. Of course, this is just sample code, you’ll need to work with your database structure and code to make it work for you… but, that should give you the framework for getting this kind of thing done.

Here’s a video walk-through of this, as well:

August 10, 2011