Reputation: 1115
Array
(
[0] => Array
(
[floor 1st Floor] => Reinforced Concrete
)
[1] => Array
(
[floor 2nd Floor] => Plain Cement
)
[2] => Array
(
[floor 3rd Floor] => Plain Cement
)
[3] => Array
(
[floor 3rd Floor] => Marble
)
[4] => Array
(
[floor 4th Floor] => Marble
)
[5] => Array
(
[floor 4th Floor] => Wood
)
[6] => Array
(
[floor 3rd Floor] => eqweqw
)
[7] => Array
(
[wall 1st Floor] => Reinforced Concrete
)
[8] => Array
(
[wall 2nd Floor] => Plain Cement
)
[9] => Array
(
[wall 4th Floor] => Plain Cement
)
[10] => Array
(
[wall 3rd Floor] => CHB
)
[11] => Array
(
[wall 3rd Floor] => ewqewqq
)
[12] => Array
(
[roof] => Tiles
)
[13] => Array
(
[roof] => qweqe
)
)
I have many array from ajax request and i get all of them in php what i did is i combine them and got the above result.My problem is i cant get all the value of the return invidually. How to convert the above array into like this below. So that i can get each value using the key example
foreach ($material as $value) {
echo $value['wall 3rd Floor'];
}
Or if possible how to get all the value from first array like this echo $value['wall 3rd Floor'];
Array
(
[0] => Array
(
[floor 1st Floor] => Reinforced Concrete
[floor 2nd Floor] => Plain Cement
[floor 3rd Floor] => Plain Cement
[floor 3rd Floor] => Marble
[floor 4th Floor] => Marble
[floor 4th Floor] => Wood
[floor 3rd Floor] => eqweqw
[wall 1st Floor] => Reinforced Concrete
[wall 2nd Floor] => Plain Cement
[wall 4th Floor] => Plain Cement
[wall 3rd Floor] => CHB
[wall 3rd Floor] => ewqewqq
[roof] => Tiles
[roof] => qweqe
)
)
i tried several approach like this one from here but i didnt get the desired output
for ($i = 0; $i < count($array); $i++) {
$key=key($array);
$val=$array[$key];
if ($val<> ' ') {
echo $key ." = ". $val ." <br> ";
}
next($array);
}
Upvotes: 0
Views: 78
Reputation: 628
Have you tried something like this:
foreach(array as $key => $value)
{
echo $key ." = ". $value ."
";
}
Upvotes: 0
Reputation: 13128
You just need to double foreach()
it:
$new = array();
foreach($data as $item) {
foreach($item as $key => $value) {
$new[$key] = $value;
}
}
Then you can access it as you like:
echo $new['wall 3rd Floor'];
Alternatively, if you want a shorter loop, you could do this via harnessing key()
and current()
:
$new = array();
foreach($data as $item) {
$new[key($item)] = current($item);
}
Explanation
key()
fetches the current key of the $item
current()
fetches the current value of the $item
Upvotes: 2