PHP更改多维数组结构

时间:2017-02-21 13:17:44

标签: php arrays multidimensional-array

你好,我的多维数组看起来像这样:

array(13890) {
  [0]=>
  array(2) {
    ["Icd"]=>
    array(2) {
      ["id"]=>
      int(111)
      ["nazwa"]=>
      string(6) "DŻUMA"
    }
    ["ProjectIcd"]=>
    array(0) {
    }
  }
  [1]=>
  array(2) {
    ["Icd"]=>
    array(2) {
      ["id"]=>
      int(566)
      ["nazwa"]=>
      string(7) "ŚWINKA"
    }
    ["ProjectIcd"]=>
    array(0) {
    }
  }

等等。

我想改变它,看起来像那样:

array(13890) {
  [0]=> array(2) {
      ["id"]=>
      int(111)
      ["text"]=>
      string(6) "DŻUMA"
    }

这怎么可能呢?

我想添加,我想将数组转换为json并将其提供给ajax中的select2 js。

这是不是问题?

3 个答案:

答案 0 :(得分:3)

使用array_map函数的简短解决方案:

// $arr is your initial array

$new_arr = array_map(function($a){
    return ['id' => $a['Icd']['id'], 'text' => $a['Icd']['nazwa']];
}, $arr);

答案 1 :(得分:0)

我希望这是你想要的东西。

$res = [];
$i = 0;
foreach($array as $arr) {
       //get keys 
      if (count($arr) > 0) {
         $keys = array_keys($arr);
         // loop through the keys and fetch data of those keys
         // put in array
        foreach($keys as $key) {
            if ($arr[$key]) {
                $res[$i]['id'] = $arr[$key]['id'];
                $res[$i]['text'] = $arr[$key]['nazwa'];
            }
            $i++;
        }
   }
}

print_r($res);
// To change array to json
echo json_encode($res);

答案 2 :(得分:0)

因此,您可以简单地创建一个新数组,并根据旧数组添加所需的值。然后使用php函数json_encode()将数组转换为json字符串:

$array = array("text"=>$old_array[0]["Icd"]["nazwa"]);
echo json_encode($array);