0

I have a multidimensional array and i want to replace the timestamp field in it..

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
        )
)

I run:

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

It does work, replaces it, but i get a Warning:

Warning: Cannot use a scalar value as an array

Why? And how to solve it?

2 Answers 2

1

It looks like some of your root array elements are not arrays, like:

[new_messages] => 0

So there's no timestamp key to access. Just add:

if(!is_array($row))
  continue;
Sign up to request clarification or add additional context in comments.

Comments

0

It also wants to change the timestamp of the key new_messages, but there isn't one (it's just a single value).

Change to this

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;
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.