PHP foreach在multidimentional数组中返回最后一行

时间:2015-06-29 06:13:18

标签: php arrays

我正在尝试从多维数组中获取用户值

$array = array();

$array["id"] = "1";
$array["name"] = "name1";
$array["country"] = "country1";

$array["id"] = "2";
$array["name"] = "name2";
$array["country"] = "country2";

$array["id"] = "3";
$array["name"] = "name3";
$array["country"] = "country3";

$array["id"] = "4";
$array["name"] = "name4";
$array["country"] = "country4";

foreach($array as $e){
    print_r($e);
}

它只返回4name4country4

我需要获取像

这样的行
foreach($array as $e){
    $id=$e['id'];
    $name=$e['name'];
    $country=$e['country'];
    echo $id.'/'.$name.'/'.$country.'<br>';
}

但这给我的错误为Illegal string offset 'id' 根据我对数组的理解,这应该返回所有值,请查看为什么这个简单的数组不起作用并建议任何方法来做它

3 个答案:

答案 0 :(得分:4)

目前您正在覆盖key。需要正确添加key。你必须像 -

那样构建数组
$array[0]["id"] = "1";
$array[0]["name"] = "name1";
$array[0]["country"] = "country1";

$array[1]["id"] = "2";
$array[1]["name"] = "name2";
$array[1]["country"] = "country2";

OR

$array = array(
   0 => array('id' => 1, 'name' => 'name1', 'country' => 'country1'),
   1 => array('id' => 2, 'name' => 'name2', 'country' => 'country2'),
);

答案 1 :(得分:4)

相反,这样做是为了让你不必手动提供数组键

$array = array();

$array[] = array("id" => 123,  "name" => "Your name",  "country" =>  "UK");
$array[] = array("id" => 1342,  "name" => "Your name 2 ",  "country" =>  "UK");

然后在foreach执行此操作

foreach($array as $key => $val){

echo $key. ":     ".$val['id']. " " . $val['name'];
}

答案 2 :(得分:2)

你必须像这样创建多维数组,现在你要多次覆盖数组。

$arrays = [
  [0]=>
    ["id"] => "1",
    ["name"] => "name1",
    ["country"] => "country1"
  ], 
  [1]=>[
     ...
  ]
];
foreach($arrays as $array){
    $id=$array['id'];
    $name=$array['name'];
    $country=$array['country'];
    echo $id.'/'.$name.'/'.'$country'.'<br>';
}