1

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?

4
  • without a loop? why? what's wrong with using a loop? and what loop are you referring? foreach? Commented May 6, 2016 at 0:50
  • Will yes, surely I can use foreach as its a common way of getting the value and much easier and simplified, I just taking a way if its possible to get the value directly without looping. Commented May 6, 2016 at 0:54
  • 1
    No, there isn't any way to do it. The only direct way to access array elements is by the index. If you want to be able to access an element by category, you should make that the index of the array. Commented May 6, 2016 at 0:57
  • 1
    if you want a crowbar to hit a nail or use a laudry machine to clean the dishes, you can try regex, encode it a json string then create your pattern and get the matches Commented May 6, 2016 at 1:07

1 Answer 1

1

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.