duanpo8329 2013-01-22 04:38
浏览 64
已采纳

array_push创建新数组而不是添加

I would like to add a key=>value pair to an existing array depending on an if statement. But it keeps adding the key=>value pair as a new index.

Here is my code:

foreach ($messageRepo as $oneMessage) {
        $calculatedTime = $oneMessage->getTimeToLive();
        $creationTime = $oneMessage->getCrdate();

        $calculatedTimes = $this->androidService->renderFormat($calculatedTime);
        $expiringDate = $creationTime + $calculatedTime;

        $ausgabe[] = array(
            'Time' => key($calculatedTimes),
            'Format' => current($calculatedTimes),
            'Title' => $oneMessage->getMessageTitle(),
            'Text' => $oneMessage->getMessageText(),
            );

        if (time() > $expiringDate) {
           array_push($ausgabe[]['Expired'], $expiringDate);

            } else {
            array_push($ausgabe[]['Expiring'], $expiringDate);
            }   
    }

The dump says:

    array(60 items)
0 => array(4 items)
  Time => 0 (integer)
  Format => 'Stunden' (7 chars)
  Title => '3 wochen total neu' (18 chars)
  Text => 'dfdsfsdf fgdsfgdsgf' (19 chars)
1 => array(1 item)
  Expired => NULL

But I want Expired => NULL as field in the original index and not as a new one.

展开全部

  • 写回答

3条回答 默认 最新

  • duanjue9889 2013-01-22 04:45
    关注

    You shouldn't use array_push in this case. Use simple assignment instead. As you don't know the index of the element that you are adding, you can create the new array, set all its values and then add it to the overall array. Something like this:

    foreach ($messageRepo as $oneMessage) {
            $calculatedTime = $oneMessage->getTimeToLive();
            $creationTime = $oneMessage->getCrdate();
    
            $calculatedTimes = $this->androidService->renderFormat($calculatedTime);
            $expiringDate = $creationTime + $calculatedTime;
    
            $newval = array(
                'Time' => key($calculatedTimes),
                'Format' => current($calculatedTimes),
                'Title' => $oneMessage->getMessageTitle(),
                'Text' => $oneMessage->getMessageText(),
                );
    
            if (time() > $expiringDate) {
               $newval['Expired'] = $expiringDate;
            } else {
               $newval['Expiring'] = $expiringDate;
            }   
    
            $ausgabe[] = $newval;
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(2条)
编辑
预览

报告相同问题?

手机看
程序员都在用的中文IT技术交流社区

程序员都在用的中文IT技术交流社区

专业的中文 IT 技术社区,与千万技术人共成长

专业的中文 IT 技术社区,与千万技术人共成长

关注【CSDN】视频号,行业资讯、技术分享精彩不断,直播好礼送不停!

关注【CSDN】视频号,行业资讯、技术分享精彩不断,直播好礼送不停!

客服 返回
顶部