麻烦通过多维数组循环

时间:2012-12-04 03:16:05

标签: php arrays loops multidimensional-array

我在尝试使用PHP循环遍历多维数组时遇到了麻烦。当我使用print_r()函数时,这是我的输出:

Array ( [0] => Array ( [fname] => [sname] => [address] => [address2] => [city] => [state] => Select State [zip] => [county] => United States [phone] => [fax] => [email] => [use_email] => on )

我尝试了几种技术,但似乎都没有。任何帮助表示赞赏!

4 个答案:

答案 0 :(得分:2)

最简单的方法是使用foreach语句:

foreach($yourarray as $array_element) {
  $address = $array_element['address'];
  $fname   = $array_element['fname'];
  ...
}

答案 1 :(得分:2)

你可以通过

来做到这一点
foreach($array as  $value) {
   foreach($value as  $val) {
    echo $val;
  }
}

答案 2 :(得分:2)

您的代码是:

$set = array( 0 => array ( 'fname' => '',
                             'sname' => '',
                             'address' => '',
                             'address2' => '',
                             'city' => '',
                             'state' => 'Select State',
                             'zip' => '',
                             'county' => 'United States',
                             'phone' => '',
                             'fax' => '',
                             'email' => '',
                             'use_email' => 'on')
);

$subArray = $set[0]; // <-- key line
foreach($subArray as $k => $v) {
    printf("key: %s, value: %s\n", $k, $v);
}

输出:

key: fname, value: 
key: sname, value: 
key: address, value: 
key: address2, value: 
key: city, value: 
key: state, value: Select State
key: zip, value: 
key: county, value: United States
key: phone, value: 
key: fax, value: 
key: email, value: 
key: use_email, value: on

您需要正确访问索引数组。

答案 3 :(得分:1)

在您想要循环之前,看起来还有一个维度。试试这个。

foreach($array[0] as $key => $value) {
    echo $key, ': ', $value;
}