简体   繁体   中英

How to get the value of a key based on the known value of a sibling key from a PHP associative array?

Consider the following array:

$bookmarksIDs = [
    [
        "id"=> 33767,
        "dateAdded"=> 1551944452042
    ],
    [
        "id"=> 33743,
        "dateAdded"=> 1551944540159
    ]
]

If I know the value of id , how do I get the value of its sibling dateAdded key?

you can do something like:

foreach ($bookmarksIDs as $bookmarksID) {
    if($bookmarksID["id"] == "33767"){
        //do something
    }
}

If you want to get the value of the sibling you need to iterate over the array to find it as @MRustamzade answered.

 foreach ($bookmarksIDs as $bookmarksID) {
  if($bookmarksID["id"] == "33767"){
    //do something
   }
 }

But if you are seeking for better performance you may change the structure of the array to be indexed by id value ie:

$bookmarksIDs = [
"id_33767"=>[

    "dateAdded"=> 1551944452042
],
"id_33743"=>[
    "dateAdded"=> 1551944540159
]
]

so you can access it directly by:

 $bookmarksIDs["id_".$id/*33743*/]["dateAdded"];

In this case make sure that the value of id is unique to not override the old values

Or you can use if you want to preserve the array structure

  array_column($bookmarksIDs ,'dateAdded','id') 

to get array like :

 $bookmarksIDs = [
 "33767"=>1551944452042  
 , 
 "33743"=> 1551944540159

]

And the dateAdded it directly bookmarksIDs["33767"].

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