访问在PHP多级阵列的较低值(Accessing lower values of multileve

2019-10-20 07:07发布

我有对象的PHP数组,并想轻松搞定所有的post_id值。 我已研究过的东西像array_values和真的不知道如何处理这个事情。 是只用一个for循环和每个POST_ID添加到另一个阵列的所有帖子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 DB调用此阵:

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

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

然后$results是上面的数组

Answer 1:

只需使用一个foreach循环

foreach($result_object as $item){

    $post_id_array[] = $item->post_id;

}


Answer 2:

使用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在这种情况下,



Answer 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
)


文章来源: Accessing lower values of multilevel array in PHP