在PHP中访问较低的多级数组值

时间:2014-06-12 02:08:03

标签: php arrays wordpress list

我有一个PHP对象数组,想要轻松获取所有post_id值。我已经研究过像array_values这样的东西,我不确定该怎么做。是使用for循环并将每个post_id添加到具有所有post id的另一个数组的最佳方法吗?

感谢您的帮助!

[0] => stdClass Object
    (
        [post_id] => 70242
        [image_id] => 70244
        [large_image] => 0
    )

[1] => stdClass Object
    (
        [post_id] => 70327
        [image_id] => 70339
        [large_image] => 1
    )

[2] => stdClass Object
    (
        [post_id] => 70017
        [image_id] => 70212
        [large_image] => 1
    )

编辑: 我从WordPress数据库调用中获取此数组:

$q = <<<SQL
    SELECT post_id, image_id, large_image
    FROM $homepage_db
    ORDER BY position;
SQL;

$results = $wpdb->get_results($q);

然后$results是上面的数组

3 个答案:

答案 0 :(得分:9)

只需使用foreach循环

foreach($result_object as $item){

    $post_id_array[] = $item->post_id;

}

答案 1 :(得分:4)

使用foreach

$post_ids = array();
foreach($arr as $e) {
  $post_ids[] = $e->post_id;
}

使用array_map

$post_ids = array_map('get_post_id', $arr);
function get_post_id($e) {
  return $e->post_id;
}

在这种情况下,我更喜欢foreach

答案 2 :(得分:3)

易。使用array_map。代码如下;使用JSON进行数据测试和测试在保留您的示例结构的同时演示该概念:

//  Set the JSON string for this example.
$json_string = <<<EOT
[
    {
        "post_id": "70242",
        "image_id": "70244",
        "large_image": "0"
    },
    {
        "post_id": "70327",
        "image_id": "70339",
        "large_image": "1"
    },
    {
        "post_id": "70017",
        "image_id": "70212",
        "large_image": "1"
    }
]
EOT;

// Decode the JSON string as any array.
$json_string_decoded = json_decode($json_string);

// Use array_map to return an array telling you what items have 'distancia'.
$results = array_map(function($value) {
    return $value->post_id;
  }, $json_string_decoded);

// Dump the array to view the contents.
echo '<pre>';
print_r($results);
echo '</pre>';

转储的输出将是:

Array
(
    [0] => 70242
    [1] => 70327
    [2] => 70017
)