How can I loop over this multi dimensional array? - php

So Im trying to loop over an array of categories and sub-categories but Im having trouble with the foreach loop. Once I've got the array working Im going to create a menu where if you hover over a category, sub categories appear.
Put it this way, Im hopeless at the logic side of things :|
This is my array along with the loops I've tried:
$categories = array(
'arr' => array(
'cat'=>'sport',
'subcats'=> array(
"surfing", "basketball", "nfl", "afl"
)
),
'arr' => array(
'cat'=>'Automotive',
'subcats'=> array(
"cars", "f1", "bikes", "etc"
)
),
'arr' => array(
'cat'=>'comedy',
'subcats'=> array(
"stand up", "pranks", "...", "test"
)
)
);
//Loop1
foreach ($categories as $key => $value) {
if($key == "arr"){
foreach ($key as $key => $value) {
echo $value;
if($key == "cat"){
echo "cat";
}
else{
echo $value;
}
}
// echo $key . "<br />";
// if($key == 'subcats'){
// echo "________".$key."<br />";
// }
}
}
//Attempt number 2
foreach ($categories as $key => $value) {
if($key == "arr"){
while($key){
echo $value;
if($key == "cat"){
echo $value;
}
if($key == "subcats"){
while($key){
echo $value[$key];
}
}
}
}
}
Updated code that I tried after this
This works okay but only problem is that it will only loop through the last arr=>array() and not any of the ones before.
$i=0;
foreach ($categories as $key => $value) {
if($key == "arr"){
foreach ($categories['arr'] as $sub => $val) {
if($sub == "cat"){
echo $val . " => ";
}
else if($sub == "subcats"){
for($i=0; $i<4; $i++){
echo $val[$i] . ", ";
}
}
}
}
}

If you can reorganize your array, you can stick the categories as keys, subcategories as values:
$categories = array(
'sport' => array(
"surfing", "basketball", "nfl", "afl"
),
'Automotive' => array(
"cars", "f1", "bikes", "etc"
),
'comedy' => array(
"stand up", "pranks", "...", "test"
)
);
// Here is an imploded list, you don't need a second loop then
foreach($categories as $cat => $subcat) {
echo "<h1>".$cat."</h1>";
echo '<ul>';
echo '<li>'.implode('</li>'.PHP_EOL.'<li>',$subcat).'</li>';
echo '</ul>';
}

Related

According to what I know you cannot echo an array. You have to loop through it. Why are the values of my array printed?

I have this data:
1CPT5
'stock' => array (
'warehouse' =>
array (
'warehouse_id' => 1,
'name' => 'CPT',
),
'quantity_available' => 5,
)
3JHB21
'stock' = > array (
'warehouse' =>
array (
'warehouse_id' => 3,
'name' => 'JHB',
),
'quantity_available' => 21,
)
and this code that is looping through the above data.
foreach ($row['stock'] as $val) {
foreach ($val['warehouse'] as $warehouse => $name) {
echo $name;
}
echo $val['quantity_available'];
echo '<pre>' . var_export($val, true) . '</pre>';
}
I am trying to display the quantity_available based on the ID of the warehouse (there are 2 warehouses) The first set of data is for warehouse_id 1 with name CPT and number of items 5.
The second set of data is for warehouse_id 3 with name JHB and number of items 21.
'warehouse' is an array and according to what I know you can only loop through an array, print_r or var_dump an array. Why if I then echo $name do I see all the values of the array and how do I isolate them so I can just get the id and based on the id display the quantity associated with that id?
I finally figured it out and the following code displays the number I am after:
foreach ($row['stock_at_takealot'] as $key => $val) {
foreach ($val['warehouse'] as $key => $value) {
if ($value == 1) {
echo $val['quantity_available'];
}
}
};
but now I have another issue where all the values are displayed in one cell instead of two. What is my mistake here please?
<td class='small centerCol'>";
foreach ($row['stock_at_takealot'] as $key => $val) {
foreach ($val['warehouse'] as $key => $value) {
if ($value == 1) {
echo $val['quantity_available'];
}
}
};
"</td>
<td class='small centerCol'>";
foreach ($row['stock_at_takealot'] as $key => $val) {
foreach ($val['warehouse'] as $key => $value) {
if ($value == 3) {
echo $val['quantity_available'];
}
}
};
"</td>
<td class='small centerCol'>"

Multidimensional Array for() with different numbered elements levels

How would I write a foreach loop that would print off all information with the following multidimensional array without using any functions:
$workers = array(
"Natalie" => array
("First term" => array(
"Subworker" => "Susan",
"Length" => '1900-2000',
"Notes" => "Finished all tasks"),
"Second term" => array(
"Subworker" => "Laura",
"Length" => '1985-1986'),
),
"Laura" => array(
"First term" => array(
"Subworker" => "Sarah",
"Length" => '1999-1992'),
),
"Carolyn" => array(
"First term" => array(
"Subworker" => "Jenny",
"Length" => '1900 -1945',
"Notes" => array
("Finished all tasks",
"Did not finish all tasks",
"Completed partial tasks" )
),
),
"Jacob" => array(
"First term" => array(
"Subworker" => "Danielle",
"Length" => '1993-1994',
"Notes" => "Finished all tasks"),
),
"Jenny" => array(
"First term" => array(
"Subworker" => "Angela",
"Length" => '1999 - 2001'),
"Second term" => array(
"Subworker" => array(
"Paula" => "Let Go",
"Steve" => "Hired"),
"Length" => '1987 - 1999',
"Notes" => "Hired"),
)
);
/****So far I've done the following, but it is not printing out everything. For example, it is not printing out under Jenny, Second term, Subworker Paula and Steve./*****
foreach($workers as $worker => $value) {
foreach ($value as $newkey => $info) {
echo $worker.':<br>'.$newkey.':<br>';
foreach ($value as $newkey) {
echo 'Subworker: '.$newkey["Subkey"].'<BR>';
foreach ($value as $newkey) {
echo 'Length: '.$newkey["Length"].'<BR>';
foreach ($value as $newkey) {
echo 'Notes: '.$newkey["Notes"].'<BR>';
}
}
}
}
}
It is necessary to cross by a function and to make small tests upstream, it is always useful to avoid the return of error in environment of dev. :)
I have to add lists (ul, li) for better one reading
if (is_array($workers) && !empty($workers)) {
echo loopArray($workers);
} else {
echo "<ul><li>".$workers."</li></ul>";
}
function loopArray($array)
{
$result = "";
$result .= "<ul>";
foreach ($array as $item => $value) {
if (is_array($value) && !empty($value)) {
$result .= "<li>".$item;
$result .= loopArray($value)."</li>";
} else {
$result .= "<ul><li>".$item.': '.$value."</li></ul>";
}
}
$result .= "</ul>";
return $result;
}
To print the particular array you've provided, without using functions:
// workers
foreach($workers as $worker => $workerarr) {
echo $worker.":<ul>\n";
// worker terms
foreach ($workerarr as $term => $terminfo) {
echo "<li>$term:<ul>\n";
// term info
foreach ($terminfo as $type => $typevalue) {
echo "<li>$type: ";
// is type value an array?
if ( is_array($typevalue) ) {
// if so, put in list
echo "<ul>\n";
foreach ($typevalue as $label => $value) {
$label = is_int($label)? '': "$label: "; // only print text
echo "<li>$label$value</li>\n";
}
echo "</ul>";
}
// if not...
else {
echo $typevalue;
}
echo "</li>\n";
}
echo "</ul></li>\n";
}
echo "</ul>";
}
Using unordered lists to help display the information in a readable manner. To see with only break tags as in the question, see PHP Sandbox - Original
PHP Sandbox - Unordered Lists

php loop through complex posts

I am new to web programming and I have such a complex posts all over my work this was the result for a var_dump($_POST) , I am using gettype() function to determine that if the value in the $arr array is another array or not , I am not convenient of such behave of code of mine , neither the problems that I always met when going to loop for insertion
the question is if there is smarter technique to loop within like this complex posts , secondly how to catch the name,phone in the 2d array that called assistant (called assistant['name'],assistant[phone])
<?php
$arr = array(
"name"=> "mmmkkkk",
"phones"=> array(
"01553338897" ,
"09090909098"
),
"address"=> "107 ostras., Germany",
"assistant"=> array(
"name" => array(
"kmkkm",
"komar"
),
"phone"=> array(
"01043338897" ,
"09099090090"
)
)
);
foreach($arr as $key => $p_value)
{
if(gettype($p_value)=="array")
{
echo $key.":"."</br>";
foreach($p_value as $newp_value => $val )
{
if(gettype($val)=="array")
{
foreach($val as $vkey)
{
echo $vkey."</br>";
}
}
else{echo $val."</br>";}
}
}else{echo $key.":".$p_value."</br>";}
}
?>
You can use Recursive function like this.
<?php
$arr = array(
"name"=> "mmmkkkk",
"phones"=> array(
"01553338897" ,
"09090909098"
),
"address"=> "107 ostras., Germany",
"assistant"=> array(
"name" => array(
"kmkkm",
"komar"
),
"phone"=> array(
"01043338897" ,
"09099090090"
)
)
);
function rec($arr) {
foreach($arr as $key => $p_value)
{
if (is_array($p_value)) {
rec($p_value);
} else {
echo $key.":".$p_value."\n";
}
}
}
rec($arr);
?>
Think recursive
function walkThrough($array, $tabulation = 0) {
foreach($array as $key => $value) {
printf ('%s%s:', str_repeat(4*$tabulation, ' '));
if (is_array($value)) walkThrough ( $value, ($tabulation+1) );
else printf('%s<br />', $value);
}
}
Use this Recursive function
function recursivefunc($arr,$key =''){
if(is_array($arr)){
foreach($arr as $k => $v){
if (is_array($v) && !empty($v)) {
recursivefunc($v,$k);
} else {
$keys = ($key=='') ? $k : $key;
echo $keys.":".$v.'</br>';
}
}
}
}
recursivefunc($arr);
Out put :
name:mmmkkkk
phones:01553338897
phones:09090909098
address:107 ostras., Germany
name:kmkkm
name:komar
phone:01043338897
phone:09099090090

How to auto increment in sub foreach loop?

Here is the example code:
<?php
$arr = array(
array(
'company' => array(
'code' => 'ccd1',
'name' => 'cnm1'
) ,
'products' => array(
array(
'code' => 'pcd1',
'name' => 'pnm1'
) ,
array(
'code' => 'pcd2',
'name' => 'pnm2'
)
)
) ,
array(
'company' => array(
'code' => 'ccd2',
'name' => 'cnm2'
) ,
'products' => array(
array(
'code' => 'pcd1',
'name' => 'pnm1'
) ,
array(
'code' => 'pcd2',
'name' => 'pnm2'
) ,
array(
'code' => 'pcd3',
'name' => 'pnm3'
)
)
)
);
echo "<pre>"; print_r($arr); echo "</pre>";
$AI = 1;
foreach($arr as $value){
$total_products = count($value['products']);
echo $AI++.".{$value['company']['name']} ({$total_products})<br />";
foreach($value['products'] as $value2){
echo " ".$value2['name']."<br />";
}
}
I don't know how to explain it, but what I want is to add auto increment in sub foreach loop, like this:
1.cnm1 (2)
1.pnm1
2.pnm2
2.cnm2 (3)
1.pnm1
2.pnm2
3.pnm3
Usually you can just use the foreach keys plus one. As another alternative, if this is just for presentation, just use ordered lists:
echo '<ol>';
foreach($arr as $ar1) {
echo '<li>' . $ar1['company']['name'] . ' (' . count($ar1['products']) . ')</li>';
echo '<ol>';
foreach($ar1['products'] as $ar2) {
echo "<li>{$ar2['name']}</li>";
}
echo '</ol>';
}
It'll number those items accordingly. No need for addition. Plus you can use CSS to style the list,
You can access the key/index of an foreach :
foreach($arr as $i => $value){
$total_products = count($value['products']);
echo ($i+1).'.'.$value['company']['name'].' ('.$total_products .')<br />';
foreach($value['products'] as $j => $value2){
echo ' '.($j+1).'.'.$value2['name'].'<br />';
}
}
Here you go.
$arr = array(array('company'=>array('code'=>'ccd1', 'name'=>'cnm1'), 'products'=>array(array('code'=>'pcd1', 'name'=>'pnm1'), array('code'=>'pcd2', 'name'=>'pnm2'))), array('company'=>array('code'=>'ccd2', 'name'=>'cnm2'), 'products'=>array(array('code'=>'pcd1', 'name'=>'pnm1'), array('code'=>'pcd2', 'name'=>'pnm2'), array('code'=>'pcd3', 'name'=>'pnm3'))));
echo "<pre>";
print_r($arr);
echo "</pre>";
$AI = 1;
foreach($arr as $value)
{
$total_products = count($value['products']);
echo $AI++.".{$value['company']['name']} ({$total_products})<br />";
$k = 0;
foreach($value['products'] as $value2)
{
echo " ".$k++.". ".$value2['name']."<br />";
}
}
This also worked for me:
foreach($value['products'] as $key2=>$value2){
$AI2 = $key2+1;
echo " ".$AI2.".{$value2['name']}<br />";
}
You can try this:
foreach($arr as $value){
$total_products = count($value['products']);
echo $AI++.".{$value['company']['name']} ({$total_products})<br />";
$sub=1;
foreach($value['products'] as $value2){
echo " ".$sub++.'.'.$value2['name']."<br />";
}
}

Outputting Array Keys of Multi-Dimensional Array

I'm trying to write a function that takes a multi-dimensional array as input and outputs a multi-line string of keys like the following
['key']['subkey']
['key']['another_subkey']
['key']['another_subkey']['subkey_under_subkey']
['key']['yet_another_subkey']
['another_key']['etc']
Here is my attempt. It has problems when you get to the second level.
function get_array_keys_as_string($array){
$output = "";
foreach($array as $k => $v){
if(is_array($v)){
$string = get_array_keys_as_string($v);
$prepend = "['$k']";
$string = $prepend.str_replace("\n","\n".$prepend, $string);
$output .= $string;
}
else{
$output .= "['$k']\n";
}
}
return $output;
}
I know I need a recursive function, but so far my attempts have come up short.
To get the exact output you asked for use the following:
$arr = array(
"key" => array(
"subkey" => 1,
"another_subkey" => array(
"subkey_under_subkey" => 1
),
"yet_another_subkey" => 1
),
"another_key" => array(
"etc" => 1
)
);
function print_keys_recursive($array, $path = false) {
foreach($array as $key=>$value) {
if(!is_array($value)) {
echo $path."[".$key."]<br/>";
} else {
if($path) {
echo $path."[".$key."]<br/>";
}
print_keys_recursive($value, $path."[".$key."]");
}
}
return;
}
print_keys_recursive($arr);
Output:
[key][subkey]
[key][another_subkey]
[key][another_subkey][subkey_under_subkey]
[key][yet_another_subkey]
[another_key][etc]
Not sure how you want the output since you have not provided an example array, just the result, but here is an example based on the following array,
$array = array(
"key" => array(
"subkey" => 1,
"another_subkey" => array("2", "subkey_under_subkey" => 3),
"yet_another_subkey" => 4
),
"another_key" => array("etc"),
"last_key" => 0
);
Using the following function,
function recursive_keys($arr, $history = NULL)
{
foreach ($arr as $key => $value)
{
if (is_array($value))
recursive_keys($value, $history."['".$key."']");
else
echo $history."['".$key."']\n";
}
}
Output of recursive_keys($array) is,
['key']['subkey']
['key']['another_subkey']['0']
['key']['another_subkey']['subkey_under_subkey']
['key']['yet_another_subkey']
['another_key']['0']
['last_key']
Try this
function arrayMultiKeys($array,$depth = 0){
foreach($array as $k=>$v){
echo "['".$k."']";
if(is_array($v)){
arrayMultiKeys($v,$depth + 1);
}
if($depth == 0 ){
echo "<br>";
}
}
}

Categories