-1

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?

Ali Aboud
  • 329
  • 3
  • 11
grazdev
  • 1,082
  • 2
  • 15
  • 37

2 Answers2

2

you can do something like:

foreach ($bookmarksIDs as $bookmarksID) {
    if($bookmarksID["id"] == "33767"){
        //do something
    }
}
MRustamzade
  • 1,425
  • 14
  • 27
0

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"].

Ali Aboud
  • 329
  • 3
  • 11
  • 1
    You can achieve this with: `$bookmarksIDs = array_combine(array_column($bookmarksIDs, "id"), $bookmarksIDs);` – dWinder Mar 07 '19 at 08:53
  • +1 this is a way to create the indexed array but if initially the array is created in the right format it will resut in better performance, as array_combine will result in iteration over the arrray, anyway this deppends on what @grazianodev needs – Ali Aboud Mar 07 '19 at 08:55
  • @AliAboud I like your idea! However, if I structured the array as you suggest, how could I get the `id` before I get `dateAdded`? Right now, with the array as I originally presented it in the question, I do `array_column( $bookmarksIDs, 'id' )`, but of course this won't work using your array structure... I'm not very good at arrays :) – grazdev Mar 07 '19 at 10:51
  • @grazianodev check this answer to understand how array_column works https://stackoverflow.com/questions/31202835/how-to-use-array-values-as-keys-without-loops?answertab=votes#tab-top you will be able to access you target using this line `$bookmarksIDs["id_".$id/*33743*/]` – Ali Aboud Mar 07 '19 at 13:05
  • I edited my answer to consider array_column solution – Ali Aboud Mar 07 '19 at 13:13