获取多维数组中元素的值

时间:2014-08-23 21:16:11

标签: php arrays

这是我的foreach循环,用于获取多维数组中的值

$_coloredvariables = get_post_meta( $post->ID, '_coloredvariables', true );
foreach ($_coloredvariables as $key => $value) {
   var_dump($value);
}

哪个输出:

array
  'label' => string 'Color' (length=5)
  'size' => string 'small' (length=5)
  'displaytype' => string 'square' (length=6)
  'values' => 
    array
      'dark-night-angel' => 
        array
          'type' => string 'Image' (length=5)
          'color' => string '#2c4065' (length=7)
          'image' => string '' (length=0)
      'forest-green' => 
        array
          'type' => string 'Color' (length=5)
          'color' => string '#285d5f' (length=7)
          'image' => string '' (length=0)
      'voilet' => 
        array
          'type' => string 'Color' (length=5)
          'color' => string '#6539c9' (length=7)
          'image' => string '' (length=0)
      'canary-yellow' => 
        array
          'type' => string 'Color' (length=5)
          'color' => string 'grey' (length=4)
          'image' => string '' (length=0)

然后只获得值数组我可以这样做:

foreach ($_coloredvariables as $key => $value) {
    var_dump($value['values']);
}

输出:

array
  'dark-night-angel' => 
    array
      'type' => string 'Image' (length=5)
      'color' => string '#2c4065' (length=7)
      'image' => string '' (length=0)
  'forest-green' => 
    array
      'type' => string 'Color' (length=5)
      'color' => string '#285d5f' (length=7)
      'image' => string '' (length=0)
  'voilet' => 
    array
      'type' => string 'Color' (length=5)
      'color' => string '#6539c9' (length=7)
      'image' => string '' (length=0)
  'canary-yellow' => 
    array
      'type' => string 'Color' (length=5)
      'color' => string 'grey' (length=4)
      'image' => string '' (length=0)

我无法弄清楚如何在数组结构中获取这些元素

“暗一夜天使”, “森林绿”, “voilet” “淡黄色的”

不使用特定名称:

var_dump($value['values']['dark-night-angel'])

更有活力的东西,当然这不起作用:

var_dump($value['values'][0][0]);

感谢

2 个答案:

答案 0 :(得分:0)

您可以在foreach循环中添加foreach循环。

foreach($_coloredvariables as $key => $value) {
    foreach($value['values'] as $valkey => $values) {
        var_dump($valkey, $values);
    }
}

答案 1 :(得分:0)

对于1 $value(可能在那个foreach中):

$colors = array_keys($value['values']);

如果您想要$_coloredvariables中所有值中的所有颜色,那么您需要这样的预测:

$colors = array();
foreach ($_coloredvariables as $key => $value) {
  $colors = array_merge($colors, array_keys($value['values']));
}

此仅返回颜色键。不是这些元素的内容(typecolor& image)。

这就是你需要的......?