将数组内容保存到数组中

时间:2015-03-20 15:20:56

标签: php

我有这个数组。我想提取一个新数组中只有一个数组的内容([choices])。我怎么能在PHP中做到这一点?

   Array
(
    [0] => Array
        (
            [key] => field_54df3275b708a
            [label] => Idioma
            [name] => idioma
            [type] => select
            [instructions] => 
            [required] => 0
            [choices] => Array
                (
                    [Catalan] => Catalan
                    [Castellano] => Castellano
                    [Ingles] => Ingles
                )

            [default_value] => 
            [allow_null] => 0
            [multiple] => 0
            [conditional_logic] => Array
                (
                    [status] => 0
                    [rules] => Array
                        (
                            [0] => Array
                                (
                                    [field] => null
                                    [operator] => ==
                                    [value] => 
                                )

                        )

                    [allorany] => all
                )

            [order_no] => 0
        )

)

我尝试使用此代码(我认为这是一个糟糕的代码):

foreach($array as $k=>$v){
          if (is_array($v)){
            foreach($v as $l=>$w){
                if ($w){ 
                    foreach($w as $s=>$t){
                        $idiomas[]=$t.'<br />';
                    }
                }
            }
        }
    }

但它将[choices]和[conditional_logic]保存到新数组中,我只想要[选择]

非常感谢你

3 个答案:

答案 0 :(得分:0)

由于您始终在每个foreach中获取密钥,因此您可以使用它来确保它是您想要的阵列:

foreach($array as $k=>$v) {
  if (is_array($v)) {
    foreach($v as $l=>$w) {
      if ($w && $l == 'choices') { // $w is the wanted array
        foreach($w as $s=>$t) {
          $idiomas[]=$t.'<br />';
        }
      }
    }
  }
}

如果($w)

,我不确定您要测试的是什么

答案 1 :(得分:0)

$arr替换为您的实际数组,但它应该可以正常工作。

// your array (replace)
$arr = array(
    "required" => 0,
    "choices" => array(
        "Catalan" => "Catalan",
        "Castellano" => "Castellano",
        "Ingles" => "Ingles",
    ),  
    "default" => NULL,
);

// the empty resulting array
$new_arr = array();

foreach($arr["choices"] as $key)
    array_push($new_arr, $arr["choices"][$key]);

// your resulting array
print_r($new_arr);

您想要的数组保存在数组$new_arr中。

答案 2 :(得分:0)

$new_array_choices = $array[0]['choices'];

我花了一段时间来创建一个test code fiddle。我不得不手动重新创建数组。