我有一个$string
:在索引数组PHP关联数组
'Name Height Weight
John 177 142
Jill 156 123
Jacob 183 157'
而且我把它分为以下结构的$array
:
Array (
[0] => Array (
['Name'] => 'John'
['Height'] => '177'
['Weight'] => '142'
)
[1] = > Array (
['Name'] => 'Jill'
['Height'] => '156'
['Weight'] => '123'
)
[2] = > Array (
['Name'] => 'Jacob'
['Height'] => '183'
['Weight'] => '157'
)
)
使用下面的代码:
$rows = explode("\n",$string); //creates an indexed array of rows as strings
$headers = explode("\t",$rows[0]); //creates an indexed array of headers as strings
$rows = array_slice($rows,1); //removes headers from $rows
$array = Array();
foreach($rows as $row) {
$array[] = array_combine($headers, explode("\t",$row)); //creates associative arrays for each row
}
但是,我无法访问索引内部的关联数组
例如,这不起作用:
echo $array[0]['Name'];
即使echo implode(', ', array_keys($array[0]));
给出:
Name, Height, Weight
我试图访问索引数组内的关联数组的许多不同的方式,但没有运气。我究竟做错了什么?
编辑:
所以,
$string = "Name Height Weight
John 177 142
Jill 156 123
Jacob 183 157";
不工作,但
$string = "Name\tHeight\tWeight\nJohn\t177\t142\nJill\t156\t123\nJacob\t183\t157";
呢......
,所以我想的问题是:什么是区别?而我将如何解释前者的字符串为后者?
'print_r($ array)''?你看到了什么? –
Ermm nope,你的代码生成的数组没有这种格式 –
@u_mulder是的,我看到上面提到的数组结构(不包括单引号) – jeffbeene