Search for values in nested array

后端 未结 6 1358
滥情空心
滥情空心 2020-12-21 01:07

I have an array as follows

array(2) {
  [\"operator\"] => array(2) {
    [\"qty\"] => int(2)
    [\"id\"] => int(251)
  }
  [\"accessory209\"] =>         


        
6条回答
  •  星月不相逢
    2020-12-21 01:31

    I used a static method because i needed it in a class, but if you want you can use it as a simple function.

    /**
     * Given an array like this
     * array(
     *   'id' => "first",
     *   'title' => "First Toolbar",
     *   'class' => "col-md-12",
     *   'items' => array(
     *       array(
     *           'tipo' => "clientLink",
     *           'id' => "clientLinkInsert"
     *       )
     *   )
     * )
     *
     * and array search like this
     * array("items", 0, "id")
     * 
     * Find the path described by the array search, in the original array
     *
     * @param array $array source array
     * @param array $search the path to the item es. ["items", 0, "tipo"]
     * @param null|mixed $defaultIfNotFound the default value if the value is not found
     *
     * @return mixed
     */
    public static function getNestedKey($array, $search, $defaultIfNotFound = null)
    {
        if( count($search) == 0 ) return $defaultIfNotFound;
        else{
            $firstElementSearch = self::array_kshift($search);
    
            if (array_key_exists($firstElementSearch, $array)) {
                if( count($search) == 0 )
                    return $array[$firstElementSearch];
                else
                    return self::getNestedKey($array[$firstElementSearch], $search, $defaultIfNotFound);
            }else{
                return $defaultIfNotFound;
            }
        }
    }
    

提交回复
热议问题