PHP:如何将点符号键分隔为带有键前缀的数组

时间:2017-05-15 07:31:18

标签: php php-5.3 php-7 php-5.6

你好我想转换这种类型的数组

[
  "Continent.0.name" => "Europe",
  "Continent.0.value" => 25,
  "Continent.1.name" => "Asia",
  "Continent.1.value" => 4.17,
  "Total" => 190
]

进入

[

    'continent' => [
        'Europe' => 25
        'Asia' => 4.17
     ],
    'Total => 190
]
点后面的

'name'应该被指定为键,并且在dot shoudl指定为值后为'value'。

有什么想法吗?

1 个答案:

答案 0 :(得分:2)

试试这个

编辑:

<?php
$arr = [
  "Continent.0.name" => "Europe",
  "Continent.0.value" => 25,
  "Continent.1.name" => "Asia",
  "Continent.1.value" => 4.17,
  "Total" => 190
];
$return = array();
$continentIndex = array();
foreach ($arr as $key => $currCell) 
{
    $name = explode('.', $key);
    if(isset($name[2]) && $name[2] === 'name')
    {
        $return[$name[0]][$currCell] = array();
        $continentIndex[$name[1]] = $currCell;
    }
    else if(isset($name[2]) && $name[2] === 'value')
        $return[$name[0]][$continentIndex[$name[1]]] = $currCell;
    if(!isset($name[1]))
        $return[$key] = $currCell;
}
var_dump($return);
?>

返回

array (size=2)
  'Continent' => 
    array (size=2)
      'Europe' => int 25
      'Asia' => float 4.17
  'Total' => int 190