我有$string
:
'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
}
但是,我无法访问索引$array
例如,这不起作用:
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";
...确实
所以我想问的问题是:差异是什么?我如何将前一个字符串解释为后者?
答案 0 :(得分:1)
您的代码不会生成该数组结构,但可以像这样修复:
$string = 'Name Height Weight
John 177 142
Jill 156 123
Jacob 183 157';
$rows = explode("\n",$string); //creates an indexed array of rows as strings
$headers = preg_split("#\s+#",trim($rows[0], "\n\r\t ")); //creates an indexed array of headers as strings, by splitting by any white space
var_dump($headers);
$rows = array_slice($rows,1); //removes headers from $rows
$array = Array();
foreach($rows as $row) {
$array[] = array_combine($headers, preg_split("#\s+#",trim($row, "\n\r\t "))); //creates associative arrays for each row, by splitting by any white space
}
var_dump($array);
这会产生输出:
array(3) {
[0]=>
string(4) "Name"
[1]=>
string(6) "Height"
[2]=>
string(6) "Weight"
}
array(3) {
[0]=>
array(3) {
["Name"]=>
string(4) "John"
["Height"]=>
string(3) "177"
["Weight"]=>
string(3) "142"
}
[1]=>
array(3) {
["Name"]=>
string(4) "Jill"
["Height"]=>
string(3) "156"
["Weight"]=>
string(3) "123"
}
[2]=>
array(3) {
["Name"]=>
string(5) "Jacob"
["Height"]=>
string(3) "183"
["Weight"]=>
string(3) "157"
}
}
主要思想是你必须通过任何额外的空格修剪evey行字符串,并按最长的空格序列进行分割。
答案 1 :(得分:0)
//Use following code it will work as your answer
$string='Name Height Weight
John 177 142
Jill 156 123
Jacob 183 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
$headers=array_filter(explode(" ",$headers[0])); ///t convert to space and filter remove empty element
$rows = array_slice($rows,1); //removes headers from $rows
$array = Array();
foreach($rows as $row) {
$row=explode("\t",$row);
$row=array_filter(explode(" ",$row[0]));
$array[] = array_combine($headers,$row); //creates associative arrays for each row
}
//print_r($array);
echo $array[0]['Name'];