为什么我在编写数组时只得到数据的第一个字母?

时间:2013-05-01 12:46:36

标签: php arrays

我有一个数组$new_dataprint_r($new_data['comments']);的结果如下

Array (
    [id] => 1 
    [uye] => yusufalibozkir 
    [yorum] => Saffet gel beni affet 
    [post] => 1 
)

但是当我想使用foreach循环打印我的数据时:

foreach($new_data['comments'] as $comments)
{
    echo $comments['id'];
}

结果:

1yS1 

任何帮助将不胜感激。

编辑:

这个问题可能如下 我正在创建如下的数组:

$comments = $this->post_model->getComments($data['id']);
            foreach($comments as $comments)
            {
                $comments['uye'] = $this->members_model->lognick($comments['uye']);
            }

实际上,它需要在主阵列中有2个数组。因为我的表有2行。但它只返回最后的数据。

5 个答案:

答案 0 :(得分:2)

问题是当你做foreach时实际上是返回数组中的每个对象,所以当你把索引放入时,它就是字符串的索引......只需删除echo中的索引

echo $comments;

答案 1 :(得分:2)

$comments = $this->post_model->getComments($data['id']);
foreach($comments as $comments)
{
    $comments['uye'] = $this->members_model->lognick($comments['uye']);
}

此代码是PHP意外行为的示例。请注意foreach($comments as $comments) as的两边都是相同的变量,因此最终您的原始$comments变量会被$comments内的foreach的最后一个值覆盖,并缩减为注释的值数组而不是注释数组,你得到

Array (
    [id] => 1 
    [uye] => yusufalibozkir 
    [yorum] => Saffet gel beni affet 
    [post] => 1 
)

而不是包含此类数组的数组。

修复如下

$comments = $this->post_model->getComments($data['id']);
foreach($comments as $key => $comm)
{
    $comments[$key]['uye'] = $this->members_model->lognick($comm['uye']);
}

并且您的原始代码应该可以正常工作。

答案 2 :(得分:1)

试试此代码

<?php 

$new_data['comments'] =array('id' => 1 ,'uye' => 'yusufalibozkir', 'yorum' => 'Saffet gel beni affet','post' => 1);
foreach($new_data['comments'] as $comments)
            {
                echo $comments."<br/>";
            }
?>

//output: 1
          yusufalibozkir
          Saffet gel beni 
          affet
          1

答案 3 :(得分:1)

试试这个

foreach($new_data['comments'] as $comments)
{
    echo $comments."<br>"; //replace with $comments['id'];
}

<强>输出

1
yusufalibozkir
Saffet gel beni 
affet
1

答案 4 :(得分:1)

如果您有字符串,则必须使用""。 例如:

[yorum] => "Saffet gel beni affet",

如果你创建一个数组,你必须使用,来分隔元素。