List values in multi-dimensional array in php

浪尽此生 提交于 2021-02-08 06:32:26

问题


I have been working on this a while. I see multi-dimensional arrays in php are not that easy. Here is my code:

      while (list($key,$value) = each ($x))
        {
        Print "$key  => $value\n<br>\n";
        }

This works well to display the keys of the main array. what I get is :

visitors => Array 
actions => Array 
actions-average => Array 
time-average => Array 
pages-entrance => Array

What I want is the visitors and the value (number of visitors), value of actions, etc. I want to then save the value in Mysql. Some I will have to convert from a string to and int or date.

I need to list one more level deep. But I cannot see how to do this. --------------Added ----------- So what I have is an array of arrays. I need to step through each array.


回答1:


did you try print_r ?

if you need more control over formatting then embedded loops as suggested by @Nick is the best option. Although it would be more natural and safer to use foreach loops rather than while.

foreach($x as $key => $value){
  foreach( $value as $key2 => $value2){
    print "$key $key2 => $value2\n<br />\n";
  }
}

see PHP manual: each , there is a "caution" frame.

EDIT 1 I update sample code above for 2 day array.

It seems your array has more than 2 dimension. Then you should use recursion.

function my_print_r($x,$header="")
{
  foreach($x as $key => $value){
    if(is_array($value))
      my_print_r($value,$header . $key .  " " );
    else
      print "$header $key2 => $value2\n<br />\n";
  }
}



回答2:


Try loops like this code:

$arrA=array("a", "b", "c");
$arrB=array("x", "y", "z");
$x=array("visitors" => $arrA, "actions" => $arrB);
foreach($x as $key => $value)
{
   foreach($value as $v)   
      echo "$key  => $v<br>\n";
}

OUTPUT

visitors  => a<br> 
visitors  => b<br> 
visitors  => c<br> 
actions  => x<br> 
actions  => y<br> 
actions  => z<br



回答3:


the best way is var_dump($arr);

<?php

var_dump($_SERVER);

?>

with output that includes types, string length, and will iterate over objects as well.

Since you want to iterate over an array, give foreach a try:

foreach ($arr as $el)
{
    // ... Work with each element (most useful for non associative arrays, or linear arrays)
}

// or

foreach ($arr as $key => $value)
{
    // ... Work with $key and $value pairs (most useful for hashes/associative arrays)
} 


来源:https://stackoverflow.com/questions/6260565/list-values-in-multi-dimensional-array-in-php

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!