开发者

PHP: Unexpected behavior: foreach... {$array['country'][] = $value['country']}

Why does the operator

$array['country'][] return what logically would be $array[]['country']?

What I am saying is this. If you want to extract from a MySQL array, the value of ['country'] for every row, [1],[2]...[n], you have to use

$array['country'][]

despite fact that they are ordered as

$array['row#']['country']

Is this because PHP is reading something backwards, or because I am just lacking some fundamental array information?

FULL-ish code here

$result = array();
foreach($data as $value){

   $array['countr开发者_JS百科y'][] = $value['country'];
   $array['report'][] = $value['report'];
}
$data = $array;

Let me know if I am just dumb... I can't really grasp why this is working this way.


get an id from the db

    SELECT id,country,report from yourdb

    while ($row = mysql_fetch_array($result)) {
     $array['country'][$row['id']] = $row['country'];
     $array['report'][$row['id']] = $row['report'];
    }


create an id

    SELECT country,report from yourdb
    $i=0
    while ($row = mysql_fetch_array($result)) {
     $array['country'][$i] = $row['country'];
     $array['report'][$i] = $row['report'];
    $i++
    }


Why does the operator

$array['country'][]

return what logically would be $array[]['country']?

It is because you are constructing the array in that way:

If you use $array['country'][] = $value['country'];, you are adding a new value to the sub-array which is part of the containing array under the country key. So it will be mapped to $array['country'][], you cannot expect otherwise.

If you want it to map to array[]['country'], then (using part of code from @Lawrence's answer), you'd have to add the new values using explicit numerical indexes as the key:

SELECT country,report from yourdb
$i=0;
while ($row = mysql_fetch_array($result)) {
  $array[$i]['country'][] = $row['country'];
  $array[$i]['report'][] = $row['report'];
  $i++;
}


Assuming that $data has been built by you using a loop like what you pasted in the comments (while($row=mysql_fetch_assoc($result)){$data[]=$row;}) then my answer would be because that's exactly what you asked PHP to do.

The notion $data[] = some-value-here means take that value and add it with to the end of $data array with an auto-generated key I just don't care. That is, PHP will basically see what the last item's key is, add 1 and use that as the key for the item you are adding to the array.

So what you are doing with that loop is building an array whose keys are numbers starting from 0 and incrementing (+1 each cycle, this is the [] effect) and using these keys for the rows you are getting off the database result set.

If you want to access $data in the way you described, then you have to change the way you are building it. See Lawrence Cherone's answer for that.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜