附加到关联数组PHP

时间:2013-09-20 23:25:43

标签: php arrays

我必须遗漏一些显而易见的事情:我在查询运行后返回关联数组,对于每个嵌套数组,我希望追加$child['Is_Child'] = '0';当我打印出$child时1}}数组它是正确的,但$child_participants数组没有附加它;为什么呢?

if ($query->num_rows() > 0)
        {
           $child_participants= $query->result_array();
           foreach($child_participants as $child) 
             {
               $child['Is_Child'] = '0';
             }

           return $child_participants;

         }

4 个答案:

答案 0 :(得分:3)

你在php $child数组中声明它的foreach变量是不可变的,除非你告诉php使&运算符变为可变。

foreach($child_participants as &$child) 
{
    $child['Is_Child'] = '0';
}

答案 1 :(得分:3)

默认情况下,$child是原始数组元素的副本。您需要使用引用来修改实际元素:

foreach ($child_participants as &$child) {
    $child['Is_Child'] = '0';
}

&运算符使其成为引用。

答案 2 :(得分:2)

使用&$child

传递引用而不是值
foreach($child_participants as &$child)

答案 3 :(得分:2)

因为您正在调用$child,而不是父数组。

你可以这样做:

if ($query->num_rows() > 0)
{
   $child_participants= $query->result_array();
   foreach($child_participants as $key => $child) 
    {
        $child_participants[$key]["Is_Child"] = '0'; ;
    }

   return $child_participants;

}