<?php
$people = array(
'maurice' => array ('name' => 'hillary',
'age' =>20,
'education'=>'degree'),
'george' => array ('name' => 'florence',
'age' =>30,
'education'=>'diploma'),
'Michael' => array ('name' => 'Andrew',
'age' =>10,
'education'=>'certificate')
);
$countp = count($people);
//echo $people['maurice']['name'];
for ($i=0; $i < $countp; $i++) {
for ($j=0; $j < $countp[$i]; $j++) {
for ($k=0; $k < $countp[$i][$j]; $k++) {
echo $people[$i][$j][$k].'<br />';
}
}
# code...
}
?>
i am trying to loop through a multidimensional array with a for loop what could be the problem here. i have shared the code above.
You should use foreach
foreach($people as $name=>$information){
foreach($information as $informationKey=>$informationValue){
echo $informationValue;
}
}
Your array is not made of integer indices. It is make of keys.
How about we rewrite your for loop
foreach ($people as $person => $data) {
echo $person . PHP_EOL;
echo "Name : " .$data['name'] . PHP_EOL;
echo "Age : " .$data['age'] . PHP_EOL;
echo "Education : " .$data['education'] . PHP_EOL;
}
That shoud make it better!
You are using strings as keys (instead of integers), so you need to access the array like $people['maurice']['name'], instead of $people[0][0].
You only have two dimensions, so you don't need three loops
You should use foreach() http://php.net/manual/en/control-structures.foreach.php
Related
I need help with some of my code. I need to use the numbers in prijs for a calculation.
$autos = array(
"<b>Mercedes</b>" =>array(
"Kenteken" => "77NLXJ",
"Prijs" => "54800",
),
"<b>Tesla</b>" =>array(
"Kenteken" => "GV713G",
"Prijs" => "70700",
),
"<b>Porsche</b>" =>array(
"Kenteken" => "GG101K",
"Prijs" => "85000",
)
Is this possible?
$keys = array_keys($autos);
for($i = 0; $i < count($autos); $i++) {
echo $keys[$i] . "<br>";
foreach($autos[$keys[$i]] as $key => $value) {
echo $key . " : " . $value . "<br>";
}
echo "<br>";
}
To access and change them, you need to access them through the $autos array:
//by loop:
foreach($autos as $key => $auto){
//get or set them with this var
$autos[$key]["Prijs"];
}
//to get and set them directly:
$autos[0]["Prijs"];
$autos[1]["Prijs"];
$autos[2]["Prijs"];
I have a multi-dimensional array as follows:
Array
(
[lists] => Array
(
[0] => Array
(
[id] => 23ybdwhdwbed
[name] => TEST
(
[1] => Array
(
[id] => e223edsewed
[name] => TEST 2
(
)
)
I want to access the ID & name variables using a foreach loop.
I'm using this:
$x = 0;
foreach($lists as $list){
$listId = $list[$x]['id'];
$listName = $list[$x]['name'];
echo"$x | $listId $listName <br />";
$x++;
}
For some strange reason, I can only get the value of the first $listId & $name, not the second $listId or $name.
What am I doing wrong here?
You're assuming that you still need to provide the key for each child element. This is not the case.
try
foreach($lists as $list){
$listId = $list['id'];
$listName = $list['name'];
$listId $listName <br />";
}
the foreach() will iterate over them in turn.
if you do need the index number, do this instead.
foreach($lists as $x => $list){
where $x is the index.
The array you posted is wrong because it's missing closing ), so correct that (I think that is TYPO mistake)
After that you need to do it like below:-
foreach($lists['lists'] as $key=> $list){
$listId = $list['id'];
$listName = $list['name'];
echo "$key | $listId $listName <br />";
}
Output:-https://eval.in/846464
Or an one-liner code:-
foreach($lists['lists'] as $key=> $list){
echo "$key | ".$list['id']." ".$list['name']." <br />";
}
Output:-https://eval.in/846465
Your foreach iterates the first, not the second level of your multi dimensional array.
Since the first level only holds the lists array as one and only element the loop only executes once.
Pass the lists key to the foreach instead like so:
$x = 0;
foreach($lists['lists'] as $list) {
echo "$x | " . $list['id'] . " " . $list['name'] . "<br />";
++$x;
}
Also note how in here I reference the list elements by name to make it easier to read.
I think those numerical indexed will just confuse you so try this instead:
$my_array = array(array("id" => "23ybdwhdwbed", "name" => "TEST"), array("id" => "e223edsewed", "name" => "TEST 2"));
To access the values: use:
foreach($my_array as $my_data){
echo "ID:" . $my_data["id"];
echo "<br>";
echo "NAME:" .$my_data["name"];
echo "<br><br>";
}
you just need to do:
foreach($lists['list'] as $listKey=>$listValue){
$listId = $listValue['id'];
$listName = $listValue['name'];
echo"$listKey | $listId : $listName <br />";
}
Try this, I fixed your array structure to work, this is also dynamic so it does not matter how many array you have 0 -> above
$array = array(
'lists' => array(
'0' => array(
'id' => '23ybdwhdwbed',
'name' => 'TEST 1'
),
'1' => array(
'id' => 'e223edsewed',
'name' => 'TEST 2'
)
)
);
foreach ($array as $key => $value) {
for($ctr = 0; $ctr < count($value); $ctr++){
echo 'ID: ' . $value[$ctr]['id'] . '<br>';
echo 'Name: : ' . $value[$ctr]['name'] . '<br><br>';
}
}
Please can somebody help me with a solution to make a a string list of array like:
$string=array1, array2, .........., arrayn.
I need to generate this list dynamically.
Now I send it each array in list but I want to increase the numbers and I wonder how to put arrays dynamically inside the list.
In my code I have something like this:
$array[$j]
I need to create a list like this:
$string=$string.','.$array[$j]
...but it doesn't work. I can't send it as a multidimensional array.
Does anyone have any ideas?
if you are talking about a multidimensional array:
$container[0] = $string;
$container[1] = $array;
$container[2] = $my_other_array;
// ...
then for example $container[1] will contain your $array and with $container[1][$j] you can access the key $j in your original array.
My code is
$Copii = [];
$Config_Camere = [];
$nrCamere = $array['Camere'];
for ($i = 1; $i <= $nrCamere; $i++) {
if ($array['Copii_Cam' . $i] >= 1) {
for ($j = 1; $j <= $array['Copii_Cam' . $i]; $j++) {
$Copii[$j] = array_combine(['AgeQualifyingCode', 'Count', 'Age'], ['c', '1', $array['varstaCopil' . $j . '_Cam' . $i]]);
}
if ($array['Copii_Cam' . $i] == 2) {
$Config_Camere['RoomRequest'] = ['IndexNumber' => $i, 'GuestsCount' => ['GuestCount' => [['AgeQualifyingCode' => 'a', 'Count' => $array['Adulti_Cam' . $i]], $Copii[1], $Copii[2]]]];
} else if ($array['Copii_Cam' . $i] == 1) {
$Config_Camere['RoomRequest'] = ['IndexNumber' => $i, 'GuestsCount' => ['GuestCount' => [['AgeQualifyingCode' => 'a', 'Count' => $array['Adulti_Cam' . $i]], $Copii[1]]]];
}
} else {
$Config_Camere['RoomRequest'] = ['IndexNumber' => $i, 'GuestsCount' => ['GuestCount' => ['AgeQualifyingCode' => 'a', 'Count' => $array['Adulti_Cam' . $i]]]];
}
}
And if you see i want to generate dinamicaly the array $Copii
Thanks a lot
i want to send more than on array in foreach() .
i know this way is false .whats the true method ?
$Fname = [1,2,3,4,5];
$Lname = [1,2,3,4,5];
$Addrs = [1,2,3,4,5];
$Mobile = [1,2,3,4,5];
$fields = array(
'name' => 'a',
'type' => 'b',
'value' => 'n',
'show' => 'd',
);
foreach($fields as $key => $n)
{
echo " {$Fname[$key]} , {$Lname[$key]},{$Addrs[$key]} , {$Mobile[$key]},{$key} ,{$n} <br>";
}
If all your arrays have the same number of rows, you can use a for loop instead of a foreach, in conjunction with next() and current() for associative array:
for( $i = 0; $i < count($Fname); $i++ )
{
echo $Fname[$i] . PHP_EOL;
echo $Lname[$i] . PHP_EOL;
echo $Addrs[$i] . PHP_EOL;
echo $Mobile[$i] . PHP_EOL;
echo current($fields) . PHP_EOL;
next($fields);
}
The problem is that your arrays haven't same rows number...
So you have to add some condition like this:
for( $i = 0; $i < count($Fname); $i++ )
{
echo $Fname[$i] . PHP_EOL;
echo $Lname[$i] . PHP_EOL;
echo $Addrs[$i] . PHP_EOL;
echo $Mobile[$i] . PHP_EOL;
if( isset(current($fields)) )
{
echo current($fields) . PHP_EOL;
next($fields);
}
}
i know this way is false...? What's false about it?
foreach() will iterate over an array, not over multiple arrays.... if you absolutely need to iterate over multiple arrays within the same foreach() loop, you can use SPL's MultipleIterator, but it adds a lot more complexity to your code, and the approach that you've taken is as good as any
Just make sure that your keys match up in all the arrays; if they don't then you will have problems
foreach(array_values($fields) as $key => $n)
{
$k = array_keys($fields)[$key];
echo " {$Fname[$key]} , {$Lname[$key]},{$Addrs[$key]} , {$Mobile[$key]},{$k} ,{$n} <br>";
}
Instead of storing your data like that, it'd be easier to store it in an array of associative arrays:
$people = array(
array(
'firstName' => 'Bruce',
'lastName' => 'Wayne',
'address' => '123 East St. Gotham City, XX USA'
'mobile' => '847-847-8475'
),
array(
'firstName' => 'Roland',
'lastName' => 'Deschain',
'address' => 'N/A'
'mobile' => '191-919-1919'
)
);
foreach($people as $person){
echo $person['firstName'] + ', ' + $person['lastName'];
echo $person['address'] + ', ' + $person['mobile'];
}
It's just a cleaner way to store/access your data, makes it easy to use one foreach as well.
Try this code
$arr1 = array("a" => 1, "b" => 2, "c" => 3);
$arr2 = array("x" => 4, "y" => 5, "z" => 6);
foreach ($arr1 as $key => &$val) {}
foreach ($arr2 as $key => $val) {}
var_dump($arr1);
var_dump($arr2);
I'm having a hard time wrapping my head around this one. I have an array with different keys/values, I want to do a loop that allows me to put in different code wrappings. I'm working with an array that I'm trying to get as an XML.
This is an example of what I have..
I have what came with the code commented out and what I'm trying to do just below it in the foreach
// Multidimensional array
$superheroes = array(
"spider-man" => array(
"name" => "Peter Parker",
"email" => "peterparker#mail.com",
),
"super-man" => array(
"name" => "Clark Kent",
"email" => "clarkkent#mail.com",
),
"iron-man" => array(
"name" => "Harry Potter",
"email" => "harrypotter#mail.com",
)
);
// Printing all the keys and values one by one
$keys = array_keys($superheroes);
for($i = 0; $i < count($superheroes); $i++) {
echo $keys[$i] . "{<br>";
foreach($superheroes[$keys[$i]] as $key => $value) {
// echo $key . " : " . $value . "------";
echo '<wp:meta_key>'.$value['email'].'<wp:meta_key>';
echo '<wp:meta_value><![CDATA['.$value['name'].']]></wp:meta_value>';
}
echo "}<br>";
}
This is how you iterate the array, two levels deep:
foreach($superheroes as $key => $hero) {
echo $key."\n";
foreach ($hero as $heroKey => $heroValue) {
echo "\t".$heroKey."=>".$heroValue."\n";
}
}
You will have to adjust it to your output, but im showing the concept. The first foreach iterates all the heroes, and the second foreach iterates all the key/value pairs of each hero
EDIT: Hold on, its a bit unclear what you actually want. Is this what you want?
foreach($superheroes as $key => $hero) {
echo $key."\n";
echo "\t".$hero['email']."\n";
echo "\t".$hero['name']."\n";
}