PHP if in_array() how to get the key as well?

后端 未结 6 1422
死守一世寂寞
死守一世寂寞 2020-12-28 11:32

Struggling with a tiny problem.

I have an array:

Array
(
    [0] => 
    [6] => 6
    [3] => 5
    [2] => 7
)

I am chec

6条回答
  •  南笙
    南笙 (楼主)
    2020-12-28 12:03

    In case anyone need it in array of arrrays. My case was this:

    I had an array like this:

    $myArray =
    
    array:3 [▼
      0 => array:3 [▼
        0 => 2
        1 => 0
        2 => "2019-07-21 23:59:59"
      ]
      1 => array:3 [▼
        0 => 3
        1 => 2
        2 => "2019-07-21 23:59:59"
      ]
      2 => array:3 [▼
        0 => 1
        1 => 1
        2 => "2019-07-21 23:59:59"
      ]
    ]
    

    And another one like this (an array of objects):

    $Array2 = 
    
    Collection {#771 ▼
      #items: array:12 [▼
        0 => {#1047 ▼
          +"id": 2
          +"name": "demografico"
          +"dict_key": "demographic"
          +"component": "Demographic"
          +"country_id": null
          +"created_at": null
          +"updated_at": null
        }
        1 => {#1041 ▶}
        2 => {#1040 ▶}
        etc...
    

    As the OP, I had to "do something" (use values in a html php template, my case Laravel with blade) with the key where some value was in the array. For my code, I had to use this:

    foreach($Array2 as $key => $item)
        if(false !== $key = array_search($item->id, array_column($myArray, 0))
        // Note that $key is overwritten
            
    

提交回复
热议问题