当前位置: 动力学知识库 > 问答 > 编程问答 >

Can't pass Multi-Dimensional array to foreach function - PHP

问题描述:

I am trying to pass in a multi dimensional array to a foreach statement, when I do, the variable I cast the array to, loses the structure, so it can't be accessed properly.

For example -

 $unFilteredInfo = array();

$sql - ...

// execute sql

$i = 0;

while ($rows = CDB::GetAssoc($lrs))

{

$unFilteredInfo["LINE1"][$i] = $rows["LINE1"];

$unFilteredInfo["LINE2"][$i] = $rows["LINE2"];

$unFilteredInfo["LINE3"][$i] = $rows["LINE3"];

$i++;

}

// Array filled.

$arrayCount = count($unFilteredInfo); // 2547

$ii = 0;

foreach ($unFilteredInfo as $info)

{

$line1Info= $info["LINE1"]; // null..

$line2Info= $info["LINE2"]; // null..

$line3Info= $info["LINE3"]; // null..

$line1Info= $info["LINE1"][$ii]; // null..

$line2Info= $info["LINE2"][$ii]; // null..

$line3Info= $info["LINE3"][$ii]; // null..

$ii++;

}

Also, when running varDump on $info this is printed -

 array (size=2547)

0 => string 'APPO' (length=4)

1 => string 'APPX' (length=4)

2 => string 'APPO' (length=4)

3 => string 'APPX' (length=4)

4 => string 'APPI' (length=4)

5 => string 'APPO' (length=4)

..................................

For some reason, when I access the $info variable in the foreach statement, it results in null. I even tried to access the $info row data with a string key and int, still returns null.

Any ideas?

网友答案:

You're misunderstanding your own array structure. It looks like this:

[
    LINE1 => [.., .., ..],
    LINE2 => [.., .., ..],
    LINE3 => [.., .., ..]
]

When you loop through it with foreach, $info will be [.., .., ..].

To be honest, that array structure is also rather insane. Simplify it to this:

$unFilteredInfo = array();
while ($row = CDB::GetAssoc($lrs)) {
    $unFilteredInfo[] = $row;
}

Then:

foreach ($unFilteredInfo as $info) {
    echo $info['LINE1'];
    ...
}

Or just do the echo in the first loop to begin with.

分享给朋友:
您可能感兴趣的文章:
随机阅读: