Marco Datola February 2016

access element in nested array PHP - array to string conversion error

I need have an array structured like so

Array
 (
    [id] => 
    [name] => 
    [description] => 
    [table_id] => 
    [records] => Array
        (
            [0] => Array
                (
                    [id] => 
                    [table_id] => 
                    [created] => 2016-01-15T09:19:36-0700
                    [updated] => 
                    [created_by] => 
                    [updated_by] => 
                    [fields] => Array
                        (
                            [created] => 
                            [Delivery Date] => 
                            [Total Price Including Shipping] =>
                            [Enquiry Status] => 
                            [Equipment Booked 1] =>
                            [Equipment Booked 2] => 
                            [Equipment Booked 3] => 
                            [Equipment Booked 4] => 
                            [Equipment Booked 5] =>
                            [Equipment Booked 6] =>
                            [Surname] => 
                        )

                )

        )

    [record_count] => 1
)

I need to extract the [created] field from the last element of the nested array in [records]. I've tried doing the following

$target_elems = $target.['record_count'];
//print_r($target_elems);

//echo $target_elems;
//echo $target.['records'].[$target_elems].['created'];
echo '<pre>'; print_r($target); echo '<pre/>';

bur I always get Array to String conversion error (commented lines have been tested obviously).

the only generated output is

ArrayArrayArrayArray

Answers


Anant February 2016

As you said:- I need to extract the [created] field from the last element of the nested array in [records].

first count the number of records in records sub-array and then get the data:-

<?php
  $count = count($target['records']); // count number of record in records sub-array
  echo $target['records'][$count-1]['created']; // get last created from records array
?>


Ravi Hirani February 2016

You can get created field value of last record by below way.

$last_record = end($target['records']); // get the last record of an array
echo $last_record['created']; // print value of array key 'created'

Hope it will help you :)


Haridarshan February 2016

Try like this,

function ProcessData($arr){
    foreach($target as $key => $value){
        if( is_array($value) and !empty($value) ){
            ProcessData($value);
        }else{
            if($key == 'created'){
                echo $value;
            }
        }
    }
}

Post Status

Asked in February 2016
Viewed 2,194 times
Voted 11
Answered 3 times

Search




Leave an answer