Juliver Galleto
Juliver Galleto

Reputation: 9047

get the value from an object array base on its sub array directly

First, I have this multi dimensional array.

$array = array("user1" => array("name" => "Jason", "category" => "health"),
               "user2" => array("name" => "Mechelle", "category" => "Politics"));

how can I retrieved the sub array's value base on its same sub array object without using a loop? like I want to get the value of the array object named "name" from the object array named "category" that has a value of health. My expected result is "Jason" because in the array where the array object named "name" that has a value of 'Jason' belongs to a same sub array named 'category' where the value is "health". Any help, ideas, clues, recommendations, suggestions please?

Upvotes: 1

Views: 68

Answers (1)

Eric Poe
Eric Poe

Reputation: 373

You can do it without explicit loops. array_filter and array_reduce to the rescue! The following assumes that your initial array will be much larger and will probably include multiple sub-arrays with a category of "health."

$array = array(
    "user1" => array("name" => "Jason", "category" => "health"),
    "user2" => array("name" => "Mechelle", "category" => "Politics")
);

$healthUsers = array_filter($array, function($user) {
    return $user["category"] === "health";
});

$names = array_reduce($healthUsers, function($carry, $user) {
    $carry .= $user["name"] . " ";
    return $carry;
});

echo $names . PHP_EOL;

array_filter gives us a smaller array that only contains users which have a "category" of "health."

array_reduce runs through that array, extracts the names of each user, and puts it in a space-delimited string.

Upvotes: 1

Related Questions