嵌套数组中的访问元素PHP - 数组到字符串转换错误

时间:2016-02-08 10:35:11

标签: php arrays multidimensional-array

我需要一个像这样结构的数组

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
)

我需要从[records]中的嵌套数组的最后一个元素中提取[created]字段。 我尝试过以下

$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我总是得到Array to String转换错误(显然已对测试行进行了测试)。

唯一生成的输出是

ArrayArrayArrayArray

3 个答案:

答案 0 :(得分:1)

正如你所说: - I need to extract the [created] field from the last element of the nested array in [records].

首先计算records子数组中的记录数,然后获取数据: -

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

答案 1 :(得分:0)

您可以通过以下方式获取最后一条记录的created字段值。

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

希望它会对你有所帮助:)。

答案 2 :(得分:0)

试试这个,

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