I have a $string
:
'Name Height Weight
John 177 142
Jill 156 123
Jacob 183 157'
And I'm turning it into an $array
of the following structure:
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'
)
)
Using the following code:
$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
}
However, I cannot access the associative arrays inside of the indexed $array
For example, this doesn't work:
echo $array[0]['Name'];
Even though echo implode(', ', array_keys($array[0]));
gives:
Name, Height, Weight
I've tried many different ways of accessing the associative arrays inside of the indexed array, but with no luck. What am I doing wrong?
EDIT:
So,
$string = "Name Height Weight
John 177 142
Jill 156 123
Jacob 183 157";
Does not work, but
$string = "Name\tHeight\tWeight\nJohn\t177\t142\nJill\t156\t123\nJacob\t183\t157";
does...
So I suppose the question is: What's the difference? And how would I interpret the former string as the latter?