简体   繁体   中英

Get array sub-element when the array name is unique in php

I have this array object:

//$array
Array (
[#insert_long_unique_id] =>
Array ( 
[0] => WP_Post Object ( [ID] => 770  
) )
[#insert_long_unique_id] => 
Array ( 
[0] => WP_Post Object ( [ID] => 530 
) )

The #insert_long_unique_id is an auto-generated ID and I dunno which method or plugin generate it but it's always different.

I need to reach and echo the [ID] => 770 (first-element) only in my project.

You can do it through array_column()

$id_array = array_column($array,'ID');

echo $id_array[0]; //print first-id

//In case if you want to print all ID's

foreach($id_array as $id_arr){
  echo $id_arr;
}

If your array variable name is $array , then you can access to ID inside of object like this:

foreach ($array as $key => $value) {
    if (!empty($value)) { 
        if(!empty($value[0]) && is_object($value[0])){ 
            $myid = $value[0]->ID;
        }
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM