user2565853 user2565853 - 1 month ago 5
PHP Question

How to pull specific data from multidimensional array

I'm converting XML file into associative array to pull out the data, the problem is that I have to make 10 loops depends on arrays number in order to get the data.

is there a better way to get a specific column data without creating many loops? because I want to assign them to variables.

the array I'm trying to get data from

Array
(
[catalog] => Array
(
[book] => Array
(
[0] => Array
(
[took] => Array
(
[dodo] => Array
(
[ahmadz] => Array
(
[lolo] => Array
(
[author] => Ralls, Kim
[title] => Midnight Rain
[genre] => Fantasy
[price] => 5.95
[publish_date] => 2000-12-16
[description] => A former architect battles corporate zombies,
an evil sorceress, and her own childhood to become queen
of the world.
)

)

)

)

)

[1] => Array
(
[took] => Array
(
[dodo] => Array
(
[ahmadz] => Array
(
[lolo] => Array
(
[author] => Ralls, Kim
[title] => Midnight Rain
[genre] => Fantasy
[price] => 5.95
[publish_date] => 2000-12-16
[description] => A former architect battles corporate zombies,
an evil sorceress, and her own childhood to become queen
of the world.
)

)

)

)

)

)

)

)


I removed all other data to make it easier to read, but there are many other values in the array. Anyway, how can I get the value of author for example.

echo $array['author'];


assuming that I have many author data, not one as the example above

Please help!.

Answer

Try below code which will give you all authors as an array from multidimensional array without using forloops.., also if you want to retrieve other values from multidimentional array then you need to pass array key in in_array at if condition and prepare data according to your requirement...

$author_array = array();
array_walk_recursive($your_multidimentional_array, function($value, $key) {
    if (in_array($key, array("author"))) {
        global $author_array;
        $author_array[] = $value;
    }
});
print_r($author_array);

Hope this helps....

Comments