2

我在尝试使用 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

4 回答 4

2

最简单的就是使用 foreach 语句:

foreach($yourarray as $array_element) {
  $address = $array_element['address'];
  $fname   = $array_element['fname'];
  ...
}
于 2012-12-04T03:20:05.783 回答
2

你可以这样做

foreach($array as  $value) {
   foreach($value as  $val) {
    echo $val;
  }
}
于 2012-12-04T03:23:55.770 回答
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

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

于 2012-12-04T03:24:06.017 回答
1

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

foreach($array[0] as $key => $value) {
    echo $key, ': ', $value;
}
于 2012-12-04T03:19:40.003 回答