How to loop 3 dimension array using foreach PHP - php

Below is foreach and the 3 dimension arrays, no problem with the looping but i cannot sepcify which array to echo, they must me the whole arrays like echo $subvalue, any better solutions with looping 3 dimension array? i actually feel weird with this looping. Thanks in adv
foreach ($stories as $key => $story){
//echo "<br />";
foreach($story as $subkey => $subvalue){
echo $subvalue."<br />";
foreach($subvalue as $key => $subsubvalue){
echo $subsubvalue."<br />";
}
}
}
Array
(
[270] => Array
(
[uid] => 36
[user_email] => aaa#hotmail.com
[sid] => 270
[story_name] => Story C
[photo_url] => Array
(
[0] => story_photos/2012/0322/361332381418153311.jpg
[1] => story_photos/2012/0322/361332393792911587.jpg
)
[photo_added_date] => Array
(
[0] => 1332381418
[1] => 1332393792
)
)
[269] => Array
(
[uid] => 36
[user_email] => aaa#hotmail.com
[sid] => 269
[story_name] => Story B
[photo_url] => Array
(
[0] => story_photos/2012/0322/361332381406580761.jpg
)
[photo_added_date] => Array
(
[0] => 1332381406
)
)
[268] => Array
(
[uid] => 36
[user_email] => aaa#hotmail.com
[sid] => 268
[story_name] => Story A
[photo_url] => Array
(
[0] => story_photos/2012/0322/361332381393552719.jpg
)
[photo_added_date] => Array
(
[0] => 1332381393
)
)
)

Why not try this :
foreach ($stories as $key => $story){
if(is_array($story)){
foreach($story as $subkey => $subvalue){
if(is_array($subvalue)){
foreach($subvalue as $key => $subsubvalue){
echo $subsubvalue."<br />";
}
} else {
echo $subvalue."<br />";
}
}
} else {
echo $story."<br />";
}
}
Also, I am not sure because your question isn't really clear or specified.

Or
function echoArray( $array )
{
foreach ($array as $key => $cell)
{
if ( true == is_array($cell) )
{
echoArray($cell);
}
else
{
echo "$cell<br />";
}
}
}
It works for N dimensionnal array
An improved version to know the depth and use different css class for depth and to use set the tag in which the value should be added:
Eg: for depth 0 the class will by arrayclass_0, for depth 1 arrayclass_1, etc...
/**
$array : The array
$depth: The depth ( you should always set it to 0)
$cssclassprefix: The css class prefix you want to set
$tag: the default tag to use to render
$arraytagkey: An optionnal key in your array to extract the tag to use
*/
function echoArray( $array, $depth=0, $cssclassprefix='arrayclass_', $tag='div', $arraytagkey = '' )
{
if ( 0 != strcmp($arraytagkey) && isset($array[$arraytagkey]) )
{
$tag=$array[$arraytagkey];
}
foreach ($array as $key => $cell)
{
if ( true == is_array($cell) )
{
echoArray($cell, $depth+1, $cssclassprefix, $tag, $arraytagkey);
}
else
{
$matches = array();
if ( 0 != preg_match("/^(img|iframe|input)$/i",$tag) )
{
if ( 0 != strcasecmp('input',$tag) )
{
echo "<input class='$cssclassprefix$depth' value='$cell' />";
}
else
{
echo "<$tag class='$cssclassprefix$depth' src='$cell' />";
}
}
else if( 0 != preg_match("/^(br|hr)$/i",$tag) )
{
echo "$cell<$tag />";
}
else
{
echo "<$tag class='$cssclassprefix$depth'>$cell</$tag>";
}
}
}
}

This doesn't really answer your question, but note, your third loop is this:
foreach ($subvalue as $key => $subsubvalue){
But you've already used $key in the first loop:
foreach ($stories as $key => $story){
You should change the third to:
foreach ($subvalue as $subsubkey => $subsubvalue){

Are you just wanting to loop through and get access to the photo_urls and other data? If that's the case then here's a simple example of how you can access the data:
foreach($stories as $key => $story)
{
// here you can echo the $store['user_email'] etc
echo 'Email: ' . $story['user_email'] . '<br />';
// loop over the photo urls
foreach($story['photo_url'] as $photo_url)
{
echo 'Photo URL: ' . $photo_url . '<br />';
}
// loop over the photo added dates
foreach($story['photo_added_date'] as $photo_added_date)
{
echo 'Photo Date: ' . $photo_added_date . '<br />';
}
}
If you're wanting to recursively search the array then the other answers are what you want.

Related

Loop through php multi level associative array

I am struggling to return values from all layers of a multidimensional array, e.g. value then all child elements. I've tried lots of loops but can't quite get it right. Please can someone help - I've been stuck for ages! Thank you.
The array is:
Array
(
[SiteRep] => Array
( [DV] => Array
(
[Location] => Array
(
[Period] => Array
(
[0] => Array
(
[value] => 2016-12-19Z
[Rep] => Array
(
[0] => Array
(
[D] => W
[F] => 1
[G] => 9
)
[1] => Array
(
[D] => W
[F] => 0
[G] => 7
)
)
)
[1] => Array
(
[value] => 2016-12-20Z
[Rep] => Array
(
[0] => Array
(
[D] => ENE
[F] => 4
[G] => 7
)
[1] => Array
(
[D] => E
[F] => 3
[G] => 9
)
so far my code is:
$i=0;
foreach ($json_decoded['SiteRep']['DV']['Location']['Period'][$i] as $key => $value) {
if (is_array($value)){
foreach ($value as $key2 => $value2){
if (is_array($value2)){
foreach ($value2 as $key3 => $value3) {
echo $key3 . " 3: " . $value3 . "<br>";
}
} else {
echo $key2 . " 2: " . $value2 . "<br>";
}
};
} else {
echo $key . " 1: " . $value . "<br>";
}
$i++;
};
I believe you are looking for recursion. A function that calls itself. It can be tricky but it is by far the most efficient way to navigate an array of indeterminate depth.
function printStuff($stuff)
{
echo $stuff['value']
if (isset($stuff['rep']))
{
printStuff($stuff['rep']);
}
}
If you want the values to pass down simply change echo to a return value:
function printStuff($stuff)
{
$temp = $stuff['value']
if (isset($stuff['rep']))
{
$temp .= printStuff($stuff['rep']);
}
return $temp;
}
Note: recursion can cause out of memory if not set up correctly similar to an infinite loop, as the recursive function call pushes the function call onto the call stack every time. Just make sure your function call has a subset of the parameter passed in.
If your array has the constantly number of layers, you may use foreach-function for the each layer. If your array has different number of layers every time - you should use the recursion, because it's the only solution in your situation.
Something like this:
array_walk_recursive($array, function($item, $key){
//your actions
});
I've continued drilling down and managed to get all the data I need by using...
foreach ($json_decoded['SiteRep']['DV']['Location']['Period'] as $key => $value) {
if (is_array($value)){
foreach ($value as $key2 => $value2){
if (is_array($value2)){
foreach ($value2 as $key3 => $value3) {
foreach ($value3 as $key4 => $value4) {
echo $key4 . ": " . $value4 . "<br>";
}
}
} else {
echo $key2 . ": " . $value2 . "<br>";
}
};
} else {
echo $key . ": " . $value . "<br>";
}
$i++;
};
This can map the array recursivly. Preserving they keys and structure.
You can however only return a new value and not change the key. But you will know which key you are looking at and if you just want to echo it you can do that to.
array_map_assoc_recursive('callback', $array)
function callback($key, $value) {
return "new" . $value;
}
function array_map_assoc_recursive($f, array $a) {
return array_column(array_map(function ($key, $value) use ($f) {
if (is_array($value)) {
return [$key, array_map_assoc_recursive($f, $value)];
} else {
return [$key, call_user_func($f, $key, $value)];
}
}, array_keys($a), $a), 1, 0);
}

How can i return all the results from my array?

Array
(
[edit] => true
[id] => 1
[type] => Array
(
[0] => LC
)
[userid] => 1
[norooms] => 1
[park] => Central
[start] => 09:00
[end] => 11:00
[length] => 2
[student] => 79
[status] => Rejected
)
<?php
$posted_data = array();
if (!empty($_POST['edit'])) {
$posted_data = json_decode($_POST['editVal'], true);
}
print_r ($posted_data);
foreach ($posted_data as $key => $value) {
echo '<p>'.$key.'</p>';
echo '<p>'.$value.'</p>';
}
?>
The array at the top is the jason_decode returned. However with my foreach function it does not display the first index of the array within the array. ie. ( [0] => LC ).
Where am I going wrong?
You need to build a recursive function, something like:
function print_recursively(array $array)
{
foreach ($array as $key => $value)
{
if(is_array($value))
{
print_recursively($value);
}
else
{
echo '<p>'.$key.'</p>';
echo '<p>'.$value.'</p>';
}
}
}
Tune it according to your needs.
If you know there is array hierarchy to one level only
Keep printing the values and if the value is an array using is_array.. Iterate again.
foreach($dataArray as $key =>$value){
if(is_array($value)){
foreach($value as $array2Data){
echo $array2Data; //you can use keys as well
}
}
else
echo $value;
}

how to get values from php multidimensional array?

How can i get value of number and month from this array.
Array
(
[mane] => Riya
[id] => 70
[order] => Array
(
[details] => Array
(
[number] => 4112
[month] => March
)
)
)
Here is code which i had tried
foreach($order as $row) {
echo $row['details']['number'];
echo $row['details']['month'];
}
Here is a simple solution:
foreach ($order['order'] as $key => $value)
{
echo $value['number']."<BR />";
echo $value['month']."<BR />";
}
Here is a working DEMO for you
You are missing order array.
Change from
echo $row['details']['number'];
echo $row['details']['month'];
Into
echo $row['order']['details']['number'];
echo $row['order']['details']['month'];
// ^ error was here.
You can do like this
foreach($order as $key => $value){
if( is_array($value) and !empty($value) ){
foreach($value as $k => $v){
printData($v['number']);
printData($v['month']);
}
}else{
printData($value);
}
}

Fetch values from multi dimensional array

I need to fetch data from the array that I got through
print_r($result);
The array I got is
Array
(
[0] => Array
(
[id] =>
[Location] => Array
(
[img] => 177223
[name] =>
)
[Max] =>
[Total] =>
[Description] => Array
(
[Pre] =>
[Updated] =>
[Program] => Array
(
[Schedule] =>
)
)
[Staff] => Array
(
[FirstName] =>
)
)
)
I used this code
if (!empty($result))
{
foreach ($result as $res)
{
$Max = $res['Max'];
echo $Max;
echo "<br>";
if(isset($res['Location']))
{
foreach($res['Location'] as $loc)
{
$img= $loc['img'];
echo $img;
echo "<br>";
}
}
}
}
I am getting correct value for the first array (I.e Max etc) but not for Location, Description and Staff, can anyone correct my code
Location is not an array of arrays.
It is just an associative array.
if (!empty($result)) {
foreach ($result as $res) {
$Max = $res['Max'];
echo $Max;
echo "<br>";
if(isset($res['Location'])) {
$img= $res['Location']['img'];
echo $img;
echo "<br>";
}
}
}
You dont need to foreach through location, just access it's elements directly:
if(isset($res['Location']))
{
$img= $res['Location']['img'];
echo $img;
echo "<br>";
}
Or somethig like that.

PHP get value of multidimensional array and compair

I have this array $pages which spits out this data:
Array (
[Name] => Array (
[Subname] => Array (
[0] => 43.2057, -79.9632, 1, -70,-150
[1] => 140240757658.jpg
[2] => 5
[3] => 0
) )
[Name2] => Array (
[Subname2] => Array (
[0] => 43.1769, -79.4703, 5, -70,-150
[1] => 140267498933.png
[2] => 16
[3] => 0
) )
)
and I have this foreach setup:
foreach($pages as $row => $value) {
echo '<li>'.$row.'<ul>';
foreach($value as $x => $y) {
echo
'<li>
'.$x.'
</li></ul></li>';
}
}
What I am trying to do is if [3] in each of the Subname is equal to 0, then skip it from my foreach.
NOTE: Subname and Name are just examples, they will be different for each one.
This should work:
foreach ($pages as $page) {
foreach($page as $subname) {
if ($subname[3] != 0) {
/* Do whatever you want with the data of this subname */
}
}
}
Or this if you want to use the key names:
foreach ($pages as $pageKey => $page) {
foreach($page as $subnameKey => $subname) {
if ($subname[3] != 0) {
/* Do whatever you want with the data of this subname */
}
}
}
If you want to skip the sub-foreach then this is the solution
foreach($pages as $row => $value) {
if($value['Subname'][3] == 0)
continue;
echo '<li>' . $row . '<ul>';
foreach($value as $x => $y) {
echo '<li>' . $x . '</li></ul></li>';
}
}
Since this is an Associative Array you will not be able to to check
$pages['foo']['bar'][0] === 0
before the first foreach begins since we don't know the value of $pages['foo'] before hand. when we get to the check you have already output html at the point in the form of:
echo '<li>' . $row . '<ul>';

Categories