1

The following array has multiple data arrays. Some of the data arrays have field message, while others don't have.

I want to get the message and the created_time field from the arrays which have those fields.

I can get the data without the loop, for example:

$msg = $json['posts']['data'][0]['message'];

but how can I use the loop and get the message fields from all arrays which have that field.

Array
(
    [id] => 1234
    [posts] => Array
        (
            [data] => Array
                (
                    [0] => Array
                        (
                            [id] => 123_456
                            [from] => Array
                                (
                                    [name] => User Name
                                    [id] => 123
                                )

                            [message] => This is the message i want to get.
                            [privacy] => Array
                                (
                                    [value] => 
                                )

                            [type] => status
                            [status_type] => mobile_status_update
                            [created_time] => 2013-01-13T11:09:55+0000
                            [updated_time] => 2013-01-13T11:09:55+0000
                            [comments] => Array
                                (
                                    [count] => 0
                                )

2 Answers 2

2

How about:

foreach ($json['posts']['data'] as $postKey => $post) {
   if (isset($post['message']) {
      echo $post['message'];
   }
   if (isset($post['created_time']) {
      echo $post['created_time'];
   }
}

I'm assuming that 'data' is the only key of the $post array.

Sign up to request clarification or add additional context in comments.

Comments

2

You must ensure that $data['message'] isset(). If it is, I assume that $data['created_time'] is also present, so there is no need to check for it being set.

$messages = array();
$x = 0;
foreach($json['posts']['data'] as $data){
    if($mes = isset($data['message'])){
        $message[$x]['message'] = $mes;
        $message[$x]['created_time'] = $data['created_time'];
        $x++;
    }
}

2 Comments

$json['data'] is not set. Look at the original array.
$json['posts']['data'], my mistake

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.