PHP Looping through a multi-dimensional array - php

Hi I have this multi dimensional array in PHP:
$team_arrays = array (
"lakers" => array (
24 => "Bryant",
6 => "Price",
17 => "Lin"
),
"knicks" => array (
7 => "Anthony",
22 => "Shumpert",
12 => "Jackson"
),
"thunder" => array (
35 => "Durant",
0 => "Westbrook",
13 => "Miller"
)
);
I wanted to display something like this:
Team Name: lakers
Bryant = 24
Price = 6
Lin = 17
Team Name: knicks
Anthony = 7
Shumpert = 22
Jackson = 12
...
This is the code that I tried but seems not to work:
foreach ($team_arrays as $names => $team) {
echo "<h2>Team Name: " . $names . "</h2>";
echo "<ol>";
foreach ($team_arrays as $jersey => $names) {
echo "<li>" . $names . " = " . $jersey . "</li>";
}
echo "</ol>";
}
It generates this kind of error
Notice: Array to string conversion in
Would anyone tries for a help. Please.
I found this solution from other question but seems I can't relate to it.

There is only one small problem in your code
foreach ($team_arrays as $jersey => $names) {
^ // again looping over the same outer array?
That inner loop is wrong, you should loop over $team and not $team_arrays because your outer loop picks up each team using $team variable.
foreach ($team as $jersey => $names) {
Rest of your code and logic is already fine.
Fiddle

You need to change this line from;
foreach ($team_arrays as $jersey => $names) {
to:
foreach ($team as $jersey => $names) {

Change to foreach ($team as $jersey => $names)
Try this :
$team_arrays = array (
"lakers" => array (
24 => "Bryant",
6 => "Price",
17 => "Lin"
),
"knicks" => array (
7 => "Anthony",
22 => "Shumpert",
12 => "Jackson"
),
"thunder" => array (
35 => "Durant",
0 => "Westbrook",
13 => "Miller"
)
);
foreach ($team_arrays as $names => $team) {
echo "<h2>Team Name: " . $names . "</h2>";
echo "<ol>";
foreach ($team as $jersey => $names) {
echo "<li>" . $names . " = " . $jersey . "</li> \n";
}
echo "</ol>";
}
?>

Related

Loop Multidimensional PHP arrays

Hello I am having hard time looping through the PHP multidimensional array, I want to know the best possible way of looping an array. This is the current array that I am trying to loop through.
Array
(
[bathroom] => Array
(
[name] => Bathroom
[things] => Array
(
[0] => Array
(
[name] => Cheval Mirrow
[cubic] => .14
[quantity] => 1
)
[1] => Array
(
[name] => Carton/Wine
[cubic] => .07
[quantity] => 1
)
[2] => Array
(
[name] => Carton/picture
[cubic] => .07
[quantity] => 1
)
)
)
)
I have tried this code
$keys = array_keys($array);
for($i = 0; $i < count($array); $i++) {
echo $keys[$i] . "<br>";
foreach($array[$keys[$i]] as $key => $value) {
echo $key . " : " . $value . "<br>";
foreach($array[$value[$i]] as $key1 => $value1){
echo $key1.":". $value1."<br>";
}
}
echo "<br>";
}
I am able to get the first value now the issues is that I am not able to get the values of things array, I am getting error on this, can someone tell me where I am getting wrong on this.
Here's an example of how you can process your array:
foreach ($array as $key => $value) {
echo "$key:<br>\n";
echo " name: {$value['name']}<br>\n";
foreach ($value['things'] as $t => $thing) {
echo "\tthing $t:<br>\n";
foreach ($thing as $name => $val) {
echo "\t $name: $val<br>\n";
}
}
}
Output:
bathroom:<br>
name: Bathroom<br>
thing 0:<br>
name: ChevalMirrow<br>
cubic: 0.14<br>
quantity: 1<br>
thing 1:<br>
name: Carton/Wine<br>
cubic: 0.07<br>
quantity: 1<br>
thing 2:<br>
name: Carton/picture<br>
cubic: 0.07<br>
quantity: 1<br>
Demo on 3v4l.org
foreach ($orginalarray as $key1 => $value1){
foreach ($value1 as $key2 => $value2) {
foreach ($value2 as $key3 => $value3) {
foreach ($value3 as $key3 => $value3) {
}
}
}
}

Nested foreach Loop Execution?

I am having issue with execution of nested foreach loop execution for desired result. Below is the scenario:
Following are result in two arrays
Result1:
Array ( [0]=> Array ( [questionID] => 103 [answer] => Female [answer_cnt] => 8 )
[1] => Array ( [questionID] => 103 [answer] => Male [answer_cnt] => 9 )
)
Result2
Array ( [0] => Male [1] => Female )
my code using foreach loop is below
foreach($qrs as $qrow)
{ foreach($d as $q){
echo"<br>".$q;
echo $qrow['answer_cnt']."<br>";}
}
it will get output :
Male 8
Female8
Male 9
Female9
But My Expected output is
Female 8
Male 9
You don't need to loop on the second. Just use the first one.
foreach($qrs as $qrow) {
echo $qrow['answer'] . ' ' . $qrow['answer_cnt'] . '<br/>';
}
Its quite unclear why do you need the second array but if you want to include it (which makes no sense), just include an if.
foreach($qrs as $qrow) {
foreach($d as $q) {
if($qrow['answer'] == $q) {
echo $qrow['answer'] . ' ' . $qrow['answer_cnt'] . '<br/>';
}
}
}
Your second array is useless. just do:
foreach($qrs as $qrow)
{
echo"<br>".$qrow['answer']." ";
echo $qrow['answer_cnt']."<br>";}
}
use this...
foreach($qrs as $qrow)
{
foreach($d as $q)
{
if(in_array($q, $qrow))
{
echo"<br>".$q;
echo $qrow['answer_cnt']."<br>";
}
}
}
$arr = array(
array( 'questionID' => 103, 'answer' => 'Female', 'answer_cnt' => 8),
array( 'questionID' => 103, 'answer' => 'Male', 'answer_cnt' => 9)
);
if(count($arr) > 0) {
foreach($arr as $val) {
echo "$val[answer] $val[answer_cnt] <br />";
}
}
you can also try this one.

Trouble printing array using for loop

This is my array structure:
Array
(
[Title] => Array
(
[0] =>
[1] => One
[2] => Two
[3] => Three
[4] => Four
[5] => test
[6] => fsfd
[7] => wa
)
)
I would like to print the title and array elements so that it is structured like this:
Title
One
Two
Three
etc
I am currently having trouble doing this using the conventional for each loop:
foreach($items as $key => $notice ){?>
}?>
What is the best way to do this? Thanks
Your array is nested. Either use
foreach($items['Title'] as $key => $noticeArr ){
Or if you wish to print the keys of the first array use:
foreach($items as $key => $noticeArr ){
echo $key . "\n";
foreach($noticeArr as $notice){
echo $notice . "\n";//Wrap in <li> tags or however you want to display.
}
}
You have an array "Title" inside your array.
You could use the traditional for loop:
for ($i = 0; $i < count($yourArray['Title']); $i++) {
echo $yourArray['Title'][$i];
}
or a foreach:
foreach ($yourArray['Title'] as $item) {
echo $item;
}
You just have to iterate two times, one for the first array and another for the nested one.
$data = array(
'Title' => array('One','Two','Three'),
);
foreach ($data as $name => $results) {
echo $name . "<br />";
foreach ($results as $label)
{
echo $label . "<br />";
}
}
Try this, will work
foreach($items as $key => $noticeArr ){
echo $key . "<br />";
$array = array_filter($noticeArr, create_function('$a','return $a!=="";'));
foreach($array as $notice){
echo "<li>".$notice ."</li>"."<br />";
}
}

how can we define the index of array in foreach loop for adding/dividng two different array values

hi everyone i fetch the array by using foreach loop now how can i define the index of different elements in array for futher computation like i want the element1 of array 1 to be divided by element1 of array 2
code of for each loop
<?php
if (isset($_POST['submit'])) {
$data_t1 = $_POST['t1'];
foreach ($data_t1 as $key => $value) {
echo 'T1: ' . $value . '<br />';
echo 'T2: ' . $_POST['t2'][$key] . '<br />';
echo 'T3: ' . $_POST['a1'][$key] . '<br />';
echo 'Username: ' . $_POST['username'][$key] . '<br /><br />';
}
$data_t2 = $_POST['t2'];
$data_t3=$_POST['a1'];
$data_t4=$_POST['username'];
}
var_dump($data_t1);
var_dump($data_t2);
var_dump($data_t3);
var_dump($data_t4);
?>
now i want these array values to be used for further computation
echo "Measuring Efficiency ";
echo "<table border='1' align='center'>
<tr>
<th>Inputs</th>
<th>A</th>
<th>B</th>
<th>C</th>
</tr>";
echo "<tr>";
foreach($data_t4 as $t4)
{
echo $t4; this display the values of array 4
}
foreach($data_t1 as $t1)
{
echo $t1;
$r=round(($t1/$t4),2);
$fr=round(($t1/$t4),2);
$br=round(($t1/$t4),2);
echo "<td>" ."Room Size/Consumption". "</td>";
echo "<td>".$r. "</td>";
echo "<td>".$fr. "</td>";
echo "<td>".$br. "</td>";
echo "</tr>";
echo "<tr>";
}
?
how can i define the index of array for division of elements of two array
my result is
$data_t1 [12 12] $data_t4 [1.44 4.32] $data_t2 [2 4] $data_t3 [2 3]
i want to divide 12/1.44,2/1.44 2/1.44 n 12/4.32 4/4.32 3/4.32
how can i do ths
Is this what you mean?
$array_1 = array(10,30,50,70,90);
$array_2 = array(1,3,5,7,9);
foreach($array_1 as $i => $v){
$array_1[$i] = $array_1[$i]/$array_2[$i];
}
print_r($array_1);
Array
(
[0] => 10
[1] => 10
[2] => 10
[3] => 10
[4] => 10
)
Or do you want to do something similar with the keys, not the values like so.
$array_1 = array(
10=>234234,
30=>234,
50=>23443,
70=>234,
90=>234
);
$array_2 = array(
1=>32423,
3=>4232,
5=>2342,
7=>234,
9=>234
);
$array_a = array_keys($array_1);
$array_b = array_keys($array_2);
foreach($array_a as $i => $v){
$tmp[$i] = $array_a[$i]/$array_a[$i];
}
print_r($tmp);
Array
(
[0] => 1
[1] => 1
[2] => 1
[3] => 1
[4] => 1
)
OK, based on your edit I've made something new.
You said:
i want to divide
12/1.44
2/1.44
2/1.44
12/4.32
4/4.32
3/4.32
$data_t4 = array(1.44,4.32);
$data_t1 = array(12,12);
$data_t2 = array(2,4);
$data_t3 = array(2,3);
$nums = array(
't1'=>$data_t1,
't2'=>$data_t2,
't3'=>$data_t3,
);
$divs = $data_t4;
foreach($nums as $i => $v){
foreach($v as $ix => $vx){
foreach($divs as $dx => $dv){
$data[$i]['n:'.$vx]['d:'.$dv] = $vx/$dv;
}
}
}
print_r($data);
Array
(
[t1] => Array
(
[n:12] => Array
(
[d:1.44] => 8.3333333333333
[d:4.32] => 2.7777777777778
)
)
[t2] => Array
(
[n:2] => Array
(
[d:1.44] => 1.3888888888889
[d:4.32] => 0.46296296296296
)
[n:4] => Array
(
[d:1.44] => 2.7777777777778
[d:4.32] => 0.92592592592593
)
)
[t3] => Array
(
[n:2] => Array
(
[d:1.44] => 1.3888888888889
[d:4.32] => 0.46296296296296
)
[n:3] => Array
(
[d:1.44] => 2.0833333333333
[d:4.32] => 0.69444444444444
)
)
)

How to loop 3 dimension array using foreach 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.

Categories