Get key of multidimensional array?

后端 未结 5 1189
逝去的感伤
逝去的感伤 2020-12-03 08:07

For example, I have multidimensional array as below:

$array = array (
  0 => 
    array (
      \'id\' => \'9\',
      \'gallery_id\' => \'2\',
             


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

    Probably http://php.net/manual/en/function.array-keys.php ?

    Convert your double dimensional array on your own:

    $tmp = null
    foreach($array as $key => $value) {
      $tmp[] = $key;
    }
    
    print_r($tmp);
    
    0 讨论(0)
  • 2020-12-03 08:21

    sometimes it is to easy to find ;)

    array_keys($array);
    

    array_keys

    0 讨论(0)
  • 2020-12-03 08:22

    This is quite simple, you just need to use array_keys():

    $keys = array_keys($array);
    

    See it working

    EDIT For your search task, this function should do the job:

    function array_search_inner ($array, $attr, $val, $strict = FALSE) {
      // Error is input array is not an array
      if (!is_array($array)) return FALSE;
      // Loop the array
      foreach ($array as $key => $inner) {
        // Error if inner item is not an array (you may want to remove this line)
        if (!is_array($inner)) return FALSE;
        // Skip entries where search key is not present
        if (!isset($inner[$attr])) continue;
        if ($strict) {
          // Strict typing
          if ($inner[$attr] === $val) return $key;
        } else {
          // Loose typing
          if ($inner[$attr] == $val) return $key;
        }
      }
      // We didn't find it
      return NULL;
    }
    
    // Example usage
    $key = array_search_inner($array, 'id', 9);
    

    The fourth parameter $strict, if TRUE, will use strict type comparisons. So 9 will not work, you would have to pass '9', since the values are stored as strings. Returns the key of the first occurence of a match, NULL if the value is not found, or FALSE on error. make sure to use a strict comparison on the return value, since 0, NULL and FALSE are all possible return values and they will all evaluate to 0 if using loose integer comparisons.

    0 讨论(0)
  • 2020-12-03 08:22

    You mean something like this:

    
    function getKeys($array)
    {
        $resultArr = array();
        foreach($array as $subArr) {
            $resultArr = array_merge($resultArr, $subArr);
        }        
        return array_keys($resultArr);
    }
    
    
    
    0 讨论(0)
  • 2020-12-03 08:30

    Try this , I think it will help you.

    foreach ($array as $key=>$value)
    {
        echo $key.'<br/>';
    
        echo $value['id'].'<br/>';
        echo $value['gallery_id'].'<br/>';
        echo $value['picture'].'<br/><br/>';
    }
    
    0 讨论(0)
提交回复
热议问题