Home >Backend Development >PHP Tutorial >为什么 foreach 输出数组 元素的第一个字符

为什么 foreach 输出数组 元素的第一个字符

WBOY
WBOYOriginal
2016-06-23 13:13:441427browse

$sql=mysql_query("select b.userid,b.username,b.card_no,b.buytime,b.commission1,m.level from buybak b left joinmember m on b.userid=m.userid where m.agentid='".$user[userid]."' and b.status1>=0 " );
$array = @mysql_fetch_array($level1_orders);
    foreach ($array as $rows) {
echo $rows.'
';//循环输出两个数组的信息
echo $rows['userid'].'
';//这样却只输出了每个元素的第一字符,如username的值为test,则输出了t。这是怎么回事?
}


用while可以正常输出,我想知道怎么用foreach输出


回复讨论(解决方案)

$array = @mysql_fetch_array($level1_orders);
print_r($array); //看看是什么

$array = @mysql_fetch_array($level1_orders);
print_r($array); //看看是什么



print_r($array)只输出了一个数组,while会循环两个二维数组,两个才是对的。foreach却没办法打印下标
Array
(
    [0] => 3
    [userid] => 3
    [1] => test3
    [username] => test3
    [2] => VIP
    [card_no] => VIP
    [3] => 2016-02-16 14:53:33
    [buytime] => 2016-02-16 14:53:33
    [4] => {"1":5,"2":8,"3":10,"4":12}
    [commission1] => {"1":5,"2":8,"3":10,"4":12}
    [5] => 1
    [level] => 1
)

while循环是怎样的,打印输出看看

其次,你上边的这种foreach遍历是遍历二维数组的,但是你的$array明显就是一维数组。

$array = @mysql_fetch_array($level1_orders);
print_r($array); //看看是什么



这是while循环出来的,这个是对的。
Array
(
    [0] => Array
        (
            [0] => 2
            [id] => 2
            [1] => 3
            [userid] => 3
            [2] => test3
            [username] => test3
            [3] => VIP
            [card_no] => VIP
            [4] => 2016-02-16 14:53:33
            [buytime] => 2016-02-16 14:53:33
            [5] => {"1":5,"2":8,"3":10,"4":12}
            [commission1] => {"1":5,"2":8,"3":10,"4":12}
            [6] => 1
            [level] => 1
        )

    [1] => Array
        (
            [0] => 10
            [id] => 10
            [1] => 8
            [userid] => 8
            [2] => test8
            [username] => test8
            [3] => VIP
            [card_no] => VIP
            [4] => 2016-02-16 14:59:13
            [buytime] => 2016-02-16 14:59:13
            [5] => {"1":5,"2":8,"3":10,"4":12}
            [commission1] => {"1":5,"2":8,"3":10,"4":12}
            [6] => 1
            [level] => 1
        )

)

mysql_fetch_array($level1_orders) 返回的是一维数组
所以你需要用 while 循环执行 mysql_fetch_array 以读取全部结果

遍历一维数组只需使用一个循环,你用两个自然就不对了

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn