Ryan
Ryan

Reputation: 985

Searching an array inside an array with an unknown key

I'm working in PHP and I have an multidimensional array which contains data about user groups, the array is current set out as follows.

$groups = array(
               10 => array("name" => "Admin", (etc)), 
                5 => array("name" => "Standard", (etc))
          );

The user will have a group value, which will either be "Admin" or "Standard" but as these values are not the key value in the array, I don't know how I will be able to search for the string value within the child array.

I'm able to change to an integer based level system, but I would prefer to do it this way.

So my question is, how am I able to search a multidimensional array for a value of a subject array without knowing it's key value?

Upvotes: 1

Views: 427

Answers (2)

Philipp
Philipp

Reputation: 15629

Try this one:

$admins = array_filter($groups, function($data) {
    return $data['name'] == 'Admin';
});

Upvotes: 2

John WH Smith
John WH Smith

Reputation: 2773

Browse it :)

$admins = array();
$standards = array();
foreach($groups AS $group)
{
    // Search for administrators in the 1-dimension array.
    $admins = array_merge($admins, array_keys($group, "Admin"));

    // Search for standard users in the 1-dimension array.
    $standards = array_merge($standards, array_keys($group, "Standard"));
}

You can use functions such as array_search or array_keys once you work with 1-dimension arrays. You'll find more information about the functions above in the PHP Manual.

Upvotes: 0

Related Questions