I have an array of arrays called $excelData. print_r($excelData) returns the following:
Array (
[0] => Array (
[0] => Array (
[0] => name
[1] => test
[2] => 4
[3] => test@test.com
[4] => it4249
[5] => sha256:1000:
)
)
[1] => Array (
[0] => Array (
[0] => fseconf
[1] => test2
[2] => 3
[3] => example@test.com
[4] => ft9655
[5] => sha256:1000:
)
)
)
and I'm trying to print the 4th index in each case (i.e. it4249 and ft955) with the following code:
$query = "INSERT INTO tblTest (username, fname, surname, year, email) VALUES";
$qPart = array_fill(0, count($excelData), "(?, ?, ?, ?, ?)");
$query .= implode(",",$qPart);
$sth = $dbh->prepare($query);
$i = 1;
print_r($excelData);
echo "<br />";
echo "<br />";
Foreach($excelData As $Row){
echo "Username: ".$Row[0][4];
echo "<br />";
echo "<br />";
$sth->bindValue($i++, $Row[0][4]);
$sth->bindValue($i++, $Row[0][0]);
$sth->bindValue($i++, $Row[0][1]);
$sth->bindValue($i++, $Row[0][2]);
$sth->bindValue($i++, $Row[0][3]);
}
But it simply prints it4249 both times. Why does this not work and how do I get this right?
EDIT:
Changing my loop to pass by reference as below solves my problem but I have no idea why - any explanations?
Foreach($excelData As &$Row){
}
Nest down 3 times.
foreach ($other as $arr)
{
foreach($arr as $arr1)
{
foreach($arr1 as $k=>$v)
{
if($k==4)
{
echo $v.'<br/>';
break; // as suggested by u_mulder
}
}
}
}
OUTPUT :
it4249
ft9655
A little snippet to possibly find where it goes wrong. Place if before you define your query to see if it ouputs what you expect, and if it's ok after the query, and so on.
<?php
reset($excelData);
echo count($excelData)."<br>"; //should be 2
do{
echo 'KEY: '.key($excelData); //fist 0, then 1
$tmp=current($excelData);
echo '<pre>'.print_r($tmp,true).'</pre><br>';
}
while(next($excelData));
?>
It gives me the output you showed. If not, there's defenitely something wrong with your array.