PHP multidimensional array print to browser showing nested arrays - php

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;

Related

Manage a 4 dimensional array or a 5 dimensional with foreach statement in php

I am having a really bad time right now, since everyone on the internet is saying that PHP supports multidimensional arrays that are two, three, four, five, or more levels deep. However, arrays more than three levels deep are hard to manage for most people. So I can't find someone to help me.
A very simple example below
$documents = array(
array(
"name"=>"Markos",
"lastname"=>"papadopoulos",
"country"=>"Greece",
"nationality"=>"greek",
"job"=>"web developer",
"hobbies"=>array(
"sports"=>"boxing",
"others"=>array(
"freetime"=>"watching Tv"
)
)
)
);
foreach($documents as $document){
echo $document['name']."<br>"
.$document['lastname']."<br>"
.$document['country']."<br>"
.$document['nationality']."<br>"
.$document['job']."<br>";
foreach ($document['hobbies'] as $key=>$value){
echo $key." ".$value."<br>";
foreach ($value['others'] as $subkey=>$subvalue){
echo $subkey['freetime'];
}
}
}
I am stuck, I can't display the "others"=>array("freetime"=>"watching tv") can anyone advice me? And if I had also another array in the "others"=>array("freetime"=>"watching tv"), how could I display that array to? I am trying to learn the logic.
foreach ($documents as $key) {
echo $key['name']. '<br>';
echo $key['lastname']. '<br>';
echo $key['country']. '<br>';
echo $key['nationality']. '<br>';
echo $key['job']. '<br>';
echo $key['hobbies']['sports']. '<br>';
echo $key['hobbies']['others']['freetime']. '<br>';
}
output will be
Markos
papadopoulos
Greece
greek
web developer
boxing
watching Tv
In PHP, foreach actually have two syntaxes:
foreach($array as $element) this might means $element ends up being an array
foreach($array as $key => $value) this means that key will never be an array, it is what the key, so what you have before the => in your array, while $value can be an array.
Here is the way to follow the first syntax, mind that you don't even have to nest foreach here, as pointed out by #Nathanael's comment what you have in your array is mostly scalar, not really nested arrays.
foreach($documents as $document){
echo $document['name']."<br>".
$document['lastname']."<br>".
$document['country']."<br>".
$document['nationality']."<br>".
$document['job']."<br>".
$document['job']."<br>".
$document['hobbies']['sports']."<br>".
$document['hobbies']['others']['freetime'];
}
If you want to go in the second syntax, then it would be even better to make a recursion:
function display_multi_level_array($array) {
foreach($array as $key => $value){
if(is_array($value)) {
display_multi_level_array($value);
continue;
}
echo $key." ".$value."<br>";
}
}
display_multi_level_array($documents);
try
foreach($documents as $document){
echo $document['name']."<br>"
.$document['lastname']."<br>"
.$document['country']."<br>"
.$document['nationality']."<br>"
.$document['job']."<br>";
foreach ($document['hobbies'] as $key=>$value){
if (is_array($value)) {
foreach ($value as $subkey=>$subvalue){
echo $subvalue;
}
} else {
echo $key." ".$value."<br>";
}
}
}

How to echo out two parts of a Multidimensional Array?

The problem I am getting is when I loop through the multidimensional array, once I get to skills in the multidimensional array, it prints out:
Andrew Wiley
30
Game Designer
72000
Array
C++ Level Design Leadership
It's printing out both Array and C++ Level Design Leadership.
How do I remove the output of Array and replace it with the skills C++ Level Design Leadership without printing both?
$students = [
Andrew => [
fullName => Andrew Wiley,
age => 30,
jobTitle => Game Designer,
Salary => 72000,
skills => [C++, Level Design, Leadership]
]
];
foreach($students[Andrew] as $student) {
echo $student . <br>;
if($student == $students[Andrew][skills]) {
foreach($students[Andrew][skills] as $skill) {
echo $skill;
}
}
};
You can use a recursive function.
function printVariables($array,$level=1){
foreach($array as $value){
if(is_array($value)){
$level++;
printVariables($value,$level);
}else{
echo $level <= 2 ? "$value\n" : "$value ";
}
}
}
printVariables($students);
Or serialize it...
foreach($students as $student){
echo json_encode($student,JSON_PRETTY_PRINT);
}
Update your foreach like so:
foreach($students['Andrew'] as $student) {
echo $student . <br>;
if($student === $students['Andrew']['skills']
&& is_array($students['Andrew']['skills'])
&& count($students['Andrew']['skills']) > 0) {
echo implode(", ",$students['Andrew']['skills']);
}
}
Output:
C++, Level Design, Leadership
What this does:
If statement checks if it is equal,
Then checks if it is an array
Then checks that the array is not empty
Before finally joining up all the array elements in to a string and outputting that string with echo.
Also note the quotes around the array keys

modify array multi dimensional php

this is my script
$cellValues3 = $objPHPExcel->getActiveSheet()->rangeToArray("$columnName$startRow:$highestColumn2$lastRow");
foreach ($cellValues3 as $value){
$wh[]=$value;
}
echo "<pre>";
print_r($wh);
echo "</pre>";die();
This is result array:
https://ibb.co/kgcaBe
but I want to result array
https://ibb.co/dLP8Ez
Please help me, I very confuse make array.
Thanks
You could modify the foreach loop and use array_shift() to get each 1st and 2nd array item :
foreach ($cellValues3 as $key=>$value){
$wh[$key]['initial']=array_shift($value);
$wh[$key]['nopol']=array_shift($value);
$wh[$key]['ws']=$value;
}
echo "<pre>";
print_r($wh);
echo "</pre>";die();
So, you need to replace some keys in $value array. You can do it this way, for example:
foreach ($cellValues3 as $value){
$first_item = array_shift($value);
$second_item = array_shift($value);
$wh[] = [
'initial' => $first_item,
'nopol' => $second_item,
'ws' => $value,
];
}

Grab value of array, in array, with for each

I have the following array:
print_r($all_projects);
--------------------------------
Array (
[0] => Array (
[pro_id] => 7
[0] => 7
)
[1] => Array (
[pro_id] => 20
[0] => 20
)
)
How do I grab each pro_id in a foreach loop?
I can find quite a bit information online on how to create an array, and how to grab the key and value from an array. But I have difficulty grabbing the value of a key in an array, in an array.
I currently have this for each:
foreach ($all_projects as $project => $project_id){
echo $project_id;
}
Which in turn returns the following:
Array
Array
This makes sense to me, but how do I go deeper in the array?
foreach($all_projects as $project) {
echo $project['pro_id'];
}
try:
foreach ($all_projects as $project => $project_id){
echo $project_id['pro_id'];
}
or even cleaner to read :
foreach ($all_projects as $project){
echo $project['pro_id'];
}
foreach($all_projects as $KEY => $VALUE) {
echo "KEY: $KEY - PRO_ID: {$VALUE['pro_id']}";
}
In your case, you'd want:
foreach ($all_projects as $project_id => $project) {
echo $project_id . " = " . $project['pro_id'];
}
Now with PHP5.5, you have an easy way to do it:
foreach ($all_projects as list($id))
echo $id;
And the old way:
foreach ($all_projects as $project)
echo $project['pro_id'];
Hope it'll help you!
If we're looping through the $all_projects with foreach loop this way,
foreach ($all_projects as $key => $project) {
echo($key);
}
then $key will actually be 0, 1, etc., not 7 or 20 -- as you might intended this to be -- and $project will be the content of the project.
In your case, I presume that the "project id" you desired are stored inside the "project" array itself, so as other suggested, you should write something like
foreach($all_projects as $project) { // omitting the $key part since you don't need it
echo($project['pro_id']);
}
this will print the actual "project id", which is the pro_id that you want.
If you were to improve this code, you might want to restructure your $all_projects this way
$all_projects = array();
$all_project[7] = $some_project; // your first project with id 7
$all_project[20] = $some_other_project; // your second project with id 20
then you will be able to use your original code to loop through:
foreach($all_projects as $project_id => $project) {
echo($project_id);
}
with $project_id be 7, 20, etc., and $project be the content of your project.
Hope this answers your question!

PHP foreach of multidimensional array

I have an array and it has two arrays inside of it...I am able to access what I want for the first row by doing this...
print_r( $_SESSION['shopcart']['cart']['qty']);
How would I write that in a foreach?
Thanks,
J
foreach($_SESSION['shopcart']['cart']['qty'] as $value) {
echo $value;
}
you would do something like this:
to dump the array: $_SESSION['shopcart']['cart']
foreach($_SESSION['shopcart']['cart'] as $key=>$value){
echo $key." => ".$value."<br/>";
}
If you want to iterate through multiple dimensions, you can nest foreach as follows:
foreach($_SESSION['shopcart'] as $cart) {
foreach ($cart as $qty) {
// do something
}
}
Though I'd need a little more information about the array structure and what you really want to do in order to provide usable code, this is probably in the right ballpark.
I would recommend you you do do like this:
foreach($_SESSION['shopcart'] as $key=>$value){
if(is_array( $value ) ){
foreach($value => k1 => $v1){
//do something here if array
echo $k1." => ".$v1."<br/>";
}
}else{
//do something here if not array
}
}

Categories