如何在嵌套数组/对象中获取此信息?

时间:2012-06-15 20:34:11

标签: php arrays

print_r($rows)会返回此信息:

Array
(
    [S1 | Excellence in P-O-P Execution: Ripping Down the Roadblocks to Breakthrough In-Store Marketing] => Array
        (
            [group] => S1 | Excellence in P-O-P Execution: Ripping Down the Roadblocks to Breakthrough In-Store Marketing
            [rows] => Array
                (
                    [0] => stdClass Object
                        (
                            [nid] => 207
                            [node_title] => Excellence in P-O-P Execution: Ripping Down the Roadblocks to Breakthrough In-Store Marketing
                            [taxonomy_term_data_field_data_field_track_term_tid] => 19
                            [node_field_data_field_speaker_title] => Jon Kramer
                            [node_field_data_field_speaker_nid] => 205
                            [field_data_field_date_time_field_date_time_value] => 2012-10-16 18:00:00
                            [field_data_field_session_number_field_session_number_value] => S1
                            [field_data_field_date_time_node_entity_type] => node
                            [field_data_field_session_number_node_entity_type] => node
                            [field_data_field_track_icon_taxonomy_term_entity_type] => taxonomy_term
                            [field_data_field_job_title_node_entity_type] => node
                            [field_data_field_company_node_entity_type] => node
                            [field_data_field_hide_track_node_entity_type] => node

(我知道我错过了所有关闭的parens;回报实际上是几千行,我只是懒得经历并找到所有这些。)

我如何获取名为nid的数据?我以为它会是

$rows[0]['rows'][0]->nid

但是我得到了一个未定义的偏移错误。我绝对无法使用完整内容(S1 | Excellence等)访问阵列的第一级 - 这是动态生成的。我曾经想过,因为它是数组的第一个元素,我可以用零偏移来获得它,但显然不是。

更新

我根据下面的答案使用current()尝试过一些事情;它让我接近一级,但我仍然无法访问nid元素。

$row = current($rows);
$nid_tmp = $row['rows'];
print '<pre>'; var_dump($nid_tmp); print '</pre>';

返回

Array
(
    [0] => stdClass Object
        (
            [nid] => 207

精细;这就是我所期待的。但是当我尝试print $nid_tmp[0]->nid时,我得到“注意:试图获取非对象的属性”错误。

1 个答案:

答案 0 :(得分:2)

如果尚未开始循环遍历数组,则可以使用current()来获取第一个元素。 http://us2.php.net/manual/en/function.current.php

$row = current($rows); // returns the first element of the array
$firstObject = $row['rows'][0];
$nid = $firstObject->nid;

或者您可以使用reset()来回放指针并获取第一个元素。 http://us2.php.net/manual/en/function.reset.php

$row = reset($rows);

您也可以使用array_shift()来获取数组的第一个元素,但是当您执行此操作时,它将从数组中删除该元素。

这些功能都不关心密钥类型。