我有一个数组$结果如下
Array
( [0] => Array (
[0] => Mr
[1] => vinay
[2] => hs
[3] => tester
[4] =>vinay.hs@abc.com
[5] => 909099
[6] => Yes )
[1] => Array (
[0] => Mr
[1] => Suresh
[2] => Kumar
[3] => tester
[4] => vinay.hs@abc.com
[5] => 809090
[6] => No )
).
我想将此数组存储为
Array
([0]=>Array (
[title] => Mr
[firstname] => vinay
[lastname] => hs
[job_title] => tester
[email] =>vinay.hs@abc.com
[phone] => 909099
[is_employed] => Yes )
[1] => Array (
[title] => Mr
[firstname] => Suresh
[lastname] => Kumar
[job_title] => tester
[email] => vinay.hs@abc.com
[phone] => 809090
[is_employed] => No ) ).
解释我该怎么做
答案 0 :(得分:5)
$fp = fopen('foo.csv', 'r');
$fields = fgetcsv($fp); // assumes fields are the first row in the file
// or $fields = array('title', 'firstname', 'lastname', 'job_title', 'email', 'phone', 'is_employed');
$records = array();
while ($record = fgetcsv($fp))
{
$records[] = array_combine($fields, $record);
}
显然它需要添加错误处理。
答案 1 :(得分:3)
$newarray=array();
foreach($result as $res) {
$a = array();
$i = 0;
foreach(array('title','firstname','lastname','job_title','email','phone','is_employed') as $key) {
$a[$key] = $res[$i++];
}
$newarray[] = $a;
}
答案 2 :(得分:1)
$arr = array("title" => "Mr", "title" => "vinay", "key" => "value")
使用以下方式访问它:
$arr["title"]
答案 3 :(得分:1)
array(
array(
'title' => 'Mr',
'firstname' => 'vinay',
'lastname' => 'hs',
'job_title' => 'tester',
'email' => 'vinay.hs@abc.com',
'phone' => '909099',
'is_employed' => TRUE
),
array(
'title' => 'Mr',
'firstname' => 'Suresh',
'lastname' => 'Kumar',
'job_title' => 'tester',
'email' => 'vinay.hs@abc.com',
'phone' => '809090',
'is_employed' => FALSE
)
);
更新:
我之前的回答是愚蠢的。如果从CSV文件加载,假设数组的第一个元素是键。
您可能想要做这样的事情。
抱歉我的命名不好。
$keysArray = array_shift($arrayFromCSV);
$wantedArrayStructure = array();
foreach ($arrayFromCSV as $person) {
$item = array();
foreach ($person as $key => $value) {
$item[$keysArray[$key]] = $value;
}
$wantedArrayStructure[] = $item;
}
var_dump($wantedArrayStructure);
答案 4 :(得分:0)
如果,是sql查询的结果。您应该使用函数来获得预期的结果: