Tall boY Tall boY - 1 month ago 8
PHP Question

PHP foreach returning last row in multidimentional array

I am trying get user value from multidimensional array as

$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);
}


It return me
4name4country4
only

I need to fetch rows like

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


but this gives me error as
Illegal string offset 'id'

from what I understood about array this should return all values, Please see why this simple array is not working and suggest any way to do it

Answer

Currently you are overwriting the keys. Need to add the keys properly. You have to build the array like -

$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'),
);