I have an array that has a nested array shown below, my goal is to use PHP and loop through this array pulling out both the parent and child data.
$NestedArray = array(
"Name" => array(
"Phone"=>"Text",
"Email"=>"12"
)
"Company" => array(
"Phone"=>"Text",
"Email"=>"12"
)
);
Will someone please show me how to loop through this array using php. Thank you.
Use the foreach construct
foreach($NestedArray as $sKey=>$subarray)
{
// You can print the subarray key here too
foreach($subarray as $key=>$value)
{
print $key + ": " + $value;
}
}
if you want to print for debug purposes, use print_r
print_r($NestedArray);
Related
I am trying to access data from a multidimensional array. Array $o contains arrays of with the key: product_id. The child array 'data' contains key => value pairs (or at least I think it does). The problems is that when I try to access the data later on: nothing is working.
Question: How can I access this data as expected in a key => value pair method that works (like foreach($o[$_product_id]['data'] as $_attr => $_value))
Original data
$_product_id=1;
$h = array('header1','header2','header3');
$line= array(1,2,3);
$o[$_product_id]['data'] = array_combine($h,array_map('trim', $line));
I var_dumped $o[$_product_id]['data'] and I can see the data is there
$data =
array (
'header1' => 1,
'header2' => 2,
'header3' => 3,
);
Help appreciated
=======================
Loading data original method
$o[$_product_id]['data'] = array_combine($h,array_map('trim', $line));
Loading data alternative method
foreach ($h as $_atr) {
$o[$_product_id]['data'][$_atr] = trim(array_shift($line));
}
Accessing data: not working as expected
foreach($o[$_product_id]['data'] as $_attr => $_value)
echo $_attr;
echo $_value;
Okay, your problem is that your code:
foreach($o[$_product_id]['data'] as $_attr => $_value)
echo $_attr;
echo $_value;
is equivalent to:
foreach($o[$_product_id]['data'] as $_attr => $_value) {
echo $_attr;
}
echo $_value;
See? You iterate over array, but output only keys, and last value after the end.
And yes, this is the standard behaviour of a foreach without {} - after foreach definition only one line runs in a loop. All other lines are considered out of the loop. Yep, that's not like in python).
So the fix is simple - add {}:
foreach($o[$_product_id]['data'] as $_attr => $_value) {
echo $_attr;
echo $_value;
}
I am trying to solve the following problem:
Note I am new to programming and PHP and working through SAMS PHP, MySQL and Apache (Julie C. Meloni).
There is an exercise where a multidimensional array has to be created. The outer array is an associative array listing the genres of movies. The genre arrays list movies of that genre. You are then asked to print out a list of genres with the list of films associated with that genre.
My code:
<?php
$genres = array(
'Science Fiction' => array('Star Trek', 'Star Wars', 'Alien'),
'Drama' => array('Les Amant de Pont Neuf', 'War & Peace', 'Bridehead Revisited'),
'Crime' => array('Heat', 'Pulp Fiction', 'Messerine')
);
$gKeys = array_keys($genres);
foreach ($gKeys as $genre) {
print $genre."<br/>";
}
?>
This works and prints out:
Science Fiction
Drama
Crime
Here's where I am running into a wall. When I try adding another foreach loop after
print $genre;
no results appear in the browser (except results of first loop). I have tried everything. For example:
starting by using the array_value() function applied to $genre and then try a foreach on the array returned.
In the textbook there is also a while (list($x) = ($y)) mechanism mentioned.
I thoroughly re-read the array chapter and have looked elsewhere to no avail.
perhaps I have structured the multidimensional array incorrectly? Do the second dimensional arrays need to be associative arrays also for consistency?
Your array is structured correctly. You're taking wrong array (array of just the keys) and adding another foreach loop after print $genre; hence it is not working.
No, it is not required for second dimensional arrays to be associative arrays as well.
<?php
$genres = array(
'Science Fiction' => array('Star Trek', 'Star Wars', 'Alien'),
'Drama' => array('Les Amant de Pont Neuf', 'War & Peace', 'Bridehead Revisited'),
'Crime' => array('Heat', 'Pulp Fiction', 'Messerine')
);
foreach ($genres as $genre => $movies)
{
print $genre . " - <br/>";
foreach ($movies as $movie)
{
print $movie . "<br/>";
}
print "</br>";
}
?>
Wait! Why are you doing:
$gKeys = array_keys($genres);
This just gives you a single array of keys.
Do your first loop on $genres, then inside:
foreach ($genre as $key=>$subgenre)
{
//do stuff here
}
foreach ($genres as $genrekey => $genrevalue) {
print $genrekey."<br/>";
foreach ($genrevalue as $value) {
print $value."<br/>";
}
}
function multiarray_keys($ar) {
foreach($ar as $k => $v) {
$keys[] = $k;
if (is_array($ar[$k]))
$keys = array_merge($keys, multiarray_keys($ar[$k]));
}
return $keys;
}
$gKeys = multiarray_keys($genres);
echo "<pre>";
print_r(multiarray_keys($array));
echo "</pre>";
Your outer array is an associative array with genres as keys.
To print out movies of that genre (the subarrays), use another foreach as follows:
print "<ul>";
foreach ($genres as $genre => $movies) {
print "<li>".$genre."<ul>";
foreach ($movies as $movie) {
print "<li>".$movie."</li>";
}
print "</ul></li>";
}
print "</ul>";
If you need this for seeing what data goes in an array for debugging purposes you could use PHPs var_export(), var_dump(), print_r() only to make sure the data is getting populated as you want it to. Otherwise if you want to show it in production you could do some like this:
foreach($multiDimentinalArray as $key => $value):
if(is_array($value)):
foreach($value as $k => $val):
print " $key.$k => $val";
else:
print "$key => $value";
endif;
endforeach;
I have an array which is of the following form in PHP-
Array(
0 =>
array (
0 => 'var1=\'some var1\'',
1 => 'var2=\'some_var2\'',
2 => 'var3=\'some_var3\'',
))
and I want it to appear as-
array (
0 => 'var1=\'some var1\'',
1 => 'var2=\'some_var2\'',
2 => 'var3=\'some_var3\'',
)
So how to do it?
Have you tried...
$inner_array = $outer_array[0];
var_dump($inner_array);
...?
Read here in the manual about more details to arrays in php.
Multidimensional arrays generally work as shown below
$shop = array( array("rose", 1.25 , 15),
array("daisy", 0.75 , 25),
array("orchid", 1.15 , 7)
);
echo $shop[0][0]." costs ".$shop[0][1]." and you get ".$shop[0][2];
The syntax of foreach construct is as follow:
foreach ($array_expression as $value) {
statement
}
foreach ($array_expression as $key => $value) {
statement
}
The first form loops over the array given by $array_expression. On each loop, the value of the current element is assigned to $value and the internal array pointer is advanced by one so that on the next loop, the next element is accessed.
The second form does the same thing, except that the current element’s key will be assigned to the variable $key on each loop.
The foreach syntax above is also similar to the following while construct:
while (list(, $value) = each($array_expression)) {
statement
}
while (list($key, $value) = each($array_expression)) {
statement
}
Even for loop can be used to process and loop through all elements of arrays with the following syntax:
$count = sizeof($arr_expression);
for ($i = 0; $i < $count; $i++) {
$value = $arr_express[$i];
statement
}
for ($i = 0, $item = ''; false != ($value = $arr_expression[$i]); $i++) {
statement
}
Nested loop of “foreach” can also be used to access multidimensional arrays. Here’s an example array and the way to access its value data. For example:
foreach ($array_expression as $arr_value) {
foreach ($array_value as $value) {
statement
}
}
Here’s an example code to access an array:
$contents = array(
"website_1" => array("name" => "StackOverFlow",
"url" => "http://www.stackoverflow.com",
"favorite" => "yes"),
"website_2" => array("name" => "Tip and Trick",
"url" => "http://www.tipandtrick.net",
"favorite" => "yes")
);
To retrieve the data, programmers can specify the keys that lead to the value directly with the following syntax, which will print the “My Digital Life”.
echo $contents['website_1']['name'];
However, the syntax above becomes unpractical when dealing with large arrays, or when the name of the keys and values changed dynamically. In this case, the “foreach” function can be used to access an array recursively.
foreach ($contests as $key => $list) {
echo "Website No.: " . $key . "\n";
echo "Name: " . $list['name'] . "\n";
echo "URL: " . $list['url'] . "\n";
}
The output will be:
Website No.: website_1
Name: StackOverFlow
URL: http://www.stackoverflow.com/
Website No.: website_2
Name: Tip and Trick
URL: http://www.tipandtrick.net/
I have a multidimensional array and I want to create new variables for each array after apllying a function. I dont really know how to use the foreach with this kind of array. Here's my code so far:
$main_array = array
(
[first_array] => array
(
['first_array1'] => product1
['first_arrayN'] => productN
)
[nth_array] => Array
(
[nth_array1] => date1
[nth_arrayN] => dateN
)
)
function getresult($something){
## some code
};
foreach ($main_array as ["{$X_array}"]["{$key}"] => $value) {
$result["{$X_array}"]["{$key}"] = getresult($value);
echo $result["{$X_array}"]["{$key}"];
};
Any help would be appreciated!
foreach ($main_array as &$inner_array) {
foreach ($inner_array as &$value) {
$value = getresult($value);
echo $value;
}
}
unset($inner_array, $value);
Note the &, which makes the variable a reference and makes modifications reflect in the original array.
Note: The unset is recommended, since the references to the last values will stay around after the loops and may cause unexpected behavior if you're reusing the variables.
foreach($main_array AS $key=>$array){
foreach($array AS $newKey=>$val){
$array[$newKey] = getResult($val);
}
$main_array[$key] = $array;
}
Im trying to add a key=>value to a existing array with a specific value.
Im basically looping through a associative array and i want to add a key=>value foreach array that has a specific id:
ex:
[0] => Array
(
[id] => 1
[blah] => value2
)
[1] => Array
(
[id] => 1
[blah] => value2
)
I want to do it so that while
foreach ($array as $arr) {
while $arr['id']==$some_id {
$array['new_key'] .=$some value
then do a array_push
}
}
so $some_value is going to be associated with the specific id.
The while loop doesn't make sense since keys are unique in an associative array. Also, are you sure you want to modify the array while you are looping through it? That may cause problems. Try this:
$tmp = new array();
foreach ($array as $arr) {
if($array['id']==$some_id) {
$tmp['new_key'] = $some_value;
}
}
array_merge($array,$tmp);
A more efficient way is this:
if(in_array($some_id,$array){
$array['new_key'] = $some_value;
}
or if its a key in the array you want to match and not the value...
if(array_key_exists($some_id,$array){
$array['new_key'] = $some_value;
}
When you use:
foreach($array as $arr){
...
}
... the $arr variable is a local copy that is only scoped to that foreach. Anything you add to it will not affect the $array variable. However, if you call $arr by reference:
foreach($array as &$arr){ // notice the &
...
}
... now if you add a new key to that array it will affect the $array through which you are looping.
I hope I understood your question correctly.
If i understood you correctly, this will be the solution:
foreach ($array as $arr) {
if ($arr['id'] == $some_id) {
$arr[] = $some value;
// or: $arr['key'] but when 'key' already exists it will be overwritten
}
}