user966582
user966582

Reputation: 3313

PHP getting data from array

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
                                )

Upvotes: 1

Views: 1285

Answers (2)

Samuel Cook
Samuel Cook

Reputation: 16828

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

Upvotes: 2

hohner
hohner

Reputation: 11578

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.

Upvotes: 2

Related Questions