替换多维数组值

时间:2013-05-12 19:42:47

标签: php arrays foreach

我有一个多维数组,我想替换它中的timestamp字段..

Array
(
    [new_messages] => 0
    [0] => Array
        (
            [id] => 42
            [sender] => 4
            [receiver] => 4
            [message] => Test
            [timestamp] => 1368178683
            [read] => 1
            [s_deleted] => 0
            [r_deleted] => 0
        )

    [1] => Array
        (
            [id] => 44
            [sender] => 4
            [receiver] => 4
            [message] => test2
            [timestamp] => 1368181485
            [read] => 1
            [s_deleted] => 0
            [r_deleted] => 0
        )
)

我跑:

foreach ($messageArray as $key => $row) {
   $orderByDate[$key]  = $row['timestamp'];
   $newTimestamp = date("d-M-Y H:i:s", $row['timestamp']);
   $messageArray[$key]['timestamp'] = $newTimestamp;
}

它确实有效,取而代之,但我收到警告:

  

警告:无法将标量值用作数组

为什么呢?以及如何解决?

2 个答案:

答案 0 :(得分:1)

看起来你的一些根数组元素不是数组,例如:

[new_messages] => 0

因此没有timestamp密钥可供访问。只需添加:

if(!is_array($row))
  continue;

答案 1 :(得分:0)

它还想更改键new_messages的时间戳,但没有一个(它只是一个值)。

更改为

foreach ($messageArray as $key => $row) {
   if (!is_array($row) || !array_key_exists('timestamp', $row)) {
     continue;
   }
   $orderByDate[$key]  = $row['timestamp'];
   $newTimestamp = date("d-M-Y H:i:s", $row['timestamp']);
   $messageArray[$key]['timestamp'] = $newTimestamp;
}