Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

php multidimensional array get values

Tags:

This is my array in php $hotels

Array (     [0] => Array         (         [hotel_name] => Name         [info] => info         [rooms] => Array             (                 [0] => Array                     (                         [room_name] => name                         [beds] => 2                         [boards] => Array                             (                                 [board_id] => 1                                 [price] =>200.00                             )                     )                 )         ) ) 

How can I get board_id and price I have tried few foreach loops but can't get the result

foreach($hotels as $row) {     foreach($row as $k)     {         foreach($k as $l)         {             echo $l['board_id'];             echo $l['price'];         }     } } 

This code didn't work.

like image 277
Petro Popelyshko Avatar asked Apr 14 '12 10:04

Petro Popelyshko


People also ask

How can get only values from multidimensional array in PHP?

First use RecursiveIteratorIterator class to flatten the multidimensional array, and then apply array_values() function to get the desired color values in a single array. Here are the references: RecursiveIteratorIterator class. array_values()

How do you get a specific value from an array?

Use filter if you want to find all items in an array that meet a specific condition. Use find if you want to check if that at least one item meets a specific condition. Use includes if you want to check if an array contains a particular value. Use indexOf if you want to find the index of a particular item in an array.

What is the use of multidimensional array How do you add and retrieve values in that array?

Multi-dimensional arrays are such type of arrays which stores an another array at each index instead of single element. In other words, define multi-dimensional arrays as array of arrays. As the name suggests, every element in this array can be an array and they can also hold other sub-arrays within.


1 Answers

This is the way to iterate on this array:

foreach($hotels as $row) {        foreach($row['rooms'] as $k) {              echo $k['boards']['board_id'];              echo $k['boards']['price'];        } } 

You want to iterate on the hotels and the rooms (the ones with numeric indexes), because those seem to be the "collections" in this case. The other arrays only hold and group properties.

like image 62
kapa Avatar answered Sep 18 '22 01:09

kapa