繁体   English   中英

PHP更改多维数组结构

[英]PHP Change multidimensional array structure

您好,我有一个多维数组,看起来像这样:

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。

会不会有问题?

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

// $arr is your initial array

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

我希望这是您想要的。

$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);

因此,您可以简单地创建一个新数组并在其中添加您想要基于旧数组的值。 然后使用php函数json_encode()将数组转换为json字符串:

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM