Link to home
Start Free TrialLog in
Avatar of APD Toronto
APD TorontoFlag for Canada

asked on

Itterate & Sort 2D Array

Hi Experts,

I'm new to PHP Arrays, but I have:

$employees = array();

$emp['name'] = 'john';
$emp['phone'] = '1234567890';
$emp['id'] = 123;

$employees[] = $emp;

$emp['name'] = 'bob';
$emp['phone'] = '9876543210';
$emp['id'] = 456;

$employees[] = $emp;

Open in new window


My questions are:

1-how can I sort these within $employees by name?

2-how can I itterate through $employees, I understand foreach ($employee as $e), but what is ($employees as $key => $value)?

Thank you
Avatar of Ray Paseur
Ray Paseur
Flag of United States of America image

You can use PHP usort() to sort multidimensional arrays.  I'll see if I can come up with an example for this test data set.
Please see: http://iconoun.com/demo/temp_apd_toronto.php

<?php // demo/temp_apd_toronto.hp
error_reporting(E_ALL);

// MAKE TEH OUTPUT EASY TO READ
echo '<pre>';

// CREATE AN EMPTY ARRAY
$employees = array();

// CREATE A SMALL ASSOCIATIVE ARRAY
$emp['name'] = 'john';
$emp['phone'] = '1234567890';
$emp['id'] = 123;

// INJECT THIS ARRAY INTO THE LARGER ARRAY
$employees[] = $emp;

// CREATE A SMALL ASSOCIATIVE ARRAY
$emp['name'] = 'bob';
$emp['phone'] = '9876543210';
$emp['id'] = 456;

// INJECT THIS ARRAY INTO THE LARGER ARRAY
$employees[] = $emp;

// SHOW THE INITIAL STATE OF THE LARGE ARRAY OF SMALLER ASSOCIATIVE ARRAYS
print_r($employees);

// CREATE A FUNCTION THAT CAN SORT THE LARGER ARRAY
// USING AN ELEMENT OF THE SMALLER ASSOCIATIVE ARRAYS
function cmp_name($a, $b)
{
    if ($a["name"] == $b["name"]) return 0;
    return ($a["name"] < $b["name"]) ? -1 : 1;
}

// RUN THE FUNCTION (MIGHT ALSO USE A CLOSURE)
usort($employees, 'cmp_name');

// SHOW THE WORK PRODUCT
var_dump($employees);

// SHOW HOW TO USE THE ITERATOR
foreach ($employees as $key => $value)
{
    echo PHP_EOL . "KEY: $key";
    echo PHP_EOL . 'VALUE: ';
    print_r($value);
    echo PHP_EOL;
}

Open in new window

Avatar of APD Toronto

ASKER

This helps, but what if in the foreach i just want to out my names?
ASKER CERTIFIED SOLUTION
Avatar of Ray Paseur
Ray Paseur
Flag of United States of America image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Thanks for the points - it's a great question.  USort() is one of the PHP features that is often overlooked.  Best of luck with your project, ~Ray