egolive egolive - 4 days ago 5
PHP Question

looping throug multidimensional array and output values

i hope somebody can help me. I read a lot about arrays and tried many of the found examples but i can't get my code to work.

First i create my array like this:

$aryUsers= array (
'users' =>
array ()
);


Than i get some data from my db which i'm saving to my array like this:

$user = array("ID" => $ID, "User" => $User, "val" => $val);
$aryUsers["users"][] = $user;


If i now print_r my array, it look like this:

Array ( [users] => Array
(
[0] => Array ( [ID] => 696 [User] => user 1 [val] => 341 )
[1] => Array ( [ID] => 708 [User] => user 2 [val] => 218 )
[2] => Array ( [ID] => 670 [User] => user 3 [val] => 73 )
[3] => Array ( [ID] => 718 [User] => user 4 [val] => 66 )
[4] => Array ( [ID] => 698 [User] => user 5 [val] => 66 )
[5] => Array ( [ID] => 721 [User] => user 6 [val] => 60 )
[6] => Array ( [ID] => 707 [User] => user 7 [val] => 60 )
[7] => Array ( [ID] => 720 [User] => user 8 [val] => 141 )
)
)


If i try to output my array with the this code (or other i tried), then i get just nothing:

$iterations = count($aryUsers[$keys[0]]);
for($i = 0; $i < $iterations; $i++) {
foreach($aryUsers as $key => $value) {
echo $value[$i];
}
}


What i'm doing wrong? Or am I doing something right at all?
Thank u for reading!

Answer

Hi given your sample data data structure.

$arrayUsers = array ( 'users' => array ( 0 => array ( 'ID' => 696, 'User' => 'user 1', 'val' => 341 ), 1 => array ( 'ID' => 708, 'User' => 'user 2', 'val' => 218 ), 2 => array ( 'ID' => 670, 'User' => 'user 3', 'val' => 73 ), 3 => array ( 'ID' => 718, 'User' => 'user 4', 'val' => 66 ), 4 => array ( 'ID' => 698, 'User' => 'user 5', 'val' => 66 ), 5 => array ( 'ID' => 721, 'User' => 'user 6', 'val' => 60 ), 6 => array ( 'ID' => 707, 'User' => 'user 7', 'val' => 60 ), 7 => array ( 'ID' => 720, 'User' => 'user 8', 'val' => 141 ), ) );

foreach ($arrayUsers as $arrayUser) { foreach ($arrayUser as $arrayUser) { echo $arrayUser['ID']. ' '. $arrayUser['User'] . ' ' . $arrayUser['val'].'<br>'; } }

Comments