Access PHP array element with a function?

后端 未结 5 813
[愿得一人]
[愿得一人] 2020-12-30 04:41

I\'m working on a program that uses PHP\'s internal array pointers to iterate along a multidimensional array. I need to get an element from the current row, and I\'ve been d

相关标签:
5条回答
  • 2020-12-30 05:03

    I very much doubt there is such a function, but it's trivial to write

    function getvalue($array, $key)
    {
      return $array[$key];
    }
    

    Edit: As of PHP 5.4, you can index array elements directly from function expressions, current($arr)['item'].

    0 讨论(0)
  • 2020-12-30 05:06

    I often use

    foreach ($arr as $key=>$val) {
       $val['item'] /*$val is the value of the array*/
       $key         /*$key is the key used */
    }
    

    instead of

    next($arr)/current($arr)

    0 讨论(0)
  • 2020-12-30 05:07

    If this does not work, how is your multidimensional array composed? A var_dump() might help.

    $subkey = 'B';
    $arr = array(
        $subkey => array(
            'AB' => 'A1',
            'AC' => 'A2'
        )
    );
    
    
    echo current($arr[$subkey]);
    next($arr[$subkey]);
    echo current($arr[$subkey]);
    
    0 讨论(0)
  • 2020-12-30 05:14

    Have you tried using one of the iterator classes yet? There might be something in there that does exactly what you want. If not, you can likely get what you want by extending the ArrayObject class.

    0 讨论(0)
  • 2020-12-30 05:29

    This function might be a bit lenghty but I use it all the time, specially in scenarious like:

    if (array_key_exists('user', $_SESSION) === true)
    {
        if (array_key_exists('level', $_SESSION['user']) === true)
        {
            $value = $_SESSION['user']['level'];
        }
    
        else
        {
            $value = 'DEFAULT VALUE IF NOT EXISTS';
        }
    }
    
    else
    {
        $value = 'DEFAULT VALUE IF NOT EXISTS';
    }
    

    Turns to this:

    Value($_SESSION, array('user', 'level'), 'DEFAULT VALUE IF NOT EXISTS');
    

    Here is the function:

    function Value($array, $key = 0, $default = false)
    {
        if (is_array($array) === true)
        {
            if (is_array($key) === true)
            {
                foreach ($key as $value)
                {
                    if (array_key_exists($value, $array) === true)
                    {
                        $array = $array[$value];
                    }
    
                    else
                    {
                        return $default;
                    }
                }
    
                return $array;
            }
    
            else if (array_key_exists($key, $array) === true)
            {
                return $array[$key];
            }
        }
    
        return $default;
    }
    

    PS: You can also use unidimensional arrays, like this:

    Value($_SERVER, 'REQUEST_METHOD', 'DEFAULT VALUE IF NOT EXISTS');
    
    0 讨论(0)
提交回复
热议问题