按爆炸键字符串分组数组

时间:2016-05-20 09:20:10

标签: php arrays input grouping explode

我尝试在爆炸键后从一个简单的数组中获取一个多维数组。 我的数组是多个输入的结果,其中名称是从md5哈希和输入的实际名称动态生成的。 我需要使用md5字符串作为键并对相对值进行分组。

$old_array = [
   'ec0e2603172c73a8b644bb9456c1ff6e-name' => 'Bruce',
   'ec0e2603172c73a8b644bb9456c1ff6e-surname' => 'Wayne',
   'ec0e2603172c73a8b644bb9456c1ff6e-city' => 'Gotham',

   '84d961568a65073a3bcf0eb216b2a576-name' => 'Clark',
   '84d961568a65073a3bcf0eb216b2a576-surname' => 'Kent',
   '84d961568a65073a3bcf0eb216b2a576-city' => 'Metropolis',
   //etc
];

这就是我想要的:

$new_array = [
    'ec0e2603172c73a8b644bb9456c1ff6e' => [
            'name' => 'Bruce',
            'surname' => 'Wayne',
            'city' => 'Gotham'
     ],
    '84d961568a65073a3bcf0eb216b2a576' => [
            'name' => 'Clark',
            'surname' => 'Kent',
            'city' => 'Metropolis'
     ] 
];

3 个答案:

答案 0 :(得分:3)

Working demo

只需使您的数组键按-展开,然后存储在具有该数组键分区值的新数组中。

$array = [
   'ec0e2603172c73a8b644bb9456c1ff6e-name' => 'Bruce',
   'ec0e2603172c73a8b644bb9456c1ff6e-surname' => 'Wayne',
   'ec0e2603172c73a8b644bb9456c1ff6e-city' => 'Gotham',

   '84d961568a65073a3bcf0eb216b2a576-name' => 'Clark',
   '84d961568a65073a3bcf0eb216b2a576-surname' => 'Kent',
   '84d961568a65073a3bcf0eb216b2a576-city' => 'Metropolis',
   //etc
];

$out = array();
foreach($array as $key => $val){
    $tmp = explode("-", $key);  
    $out[$tmp[0]][$tmp[1]] = $val;
}

echo '<pre>';
print_r($out);

答案 1 :(得分:0)

请使用以下代码

print "<pre>";
$reverse = array();
array_walk($old_array, 'walk');
$reverse = walk($reverse);

function walk($val, $key = 0)
{
    static $new_array;
    if (!$new_array)
    {
        $new_array = array();
    }
    $nums = explode('-', $key);
    if ($nums[0])
    {
        $new_array[$nums[0]][$nums[1]] = $val;
    }
    return $new_array;
}
print_r($reverse);

答案 2 :(得分:-1)

此代码输出相同:

<?php

$old_array = [
   'ec0e2603172c73a8b644bb9456c1ff6e-name' => 'Bruce',
   'ec0e2603172c73a8b644bb9456c1ff6e-surname' => 'Wayne',
   'ec0e2603172c73a8b644bb9456c1ff6e-city' => 'Gotham',

   '84d961568a65073a3bcf0eb216b2a576-name' => 'Clark',
   '84d961568a65073a3bcf0eb216b2a576-surname' => 'Kent',
   '84d961568a65073a3bcf0eb216b2a576-city' => 'Metropolis',
   //etc
];

$new_array = [];

foreach($old_array as $key => $value){

    $ky = explode('-',$key);
    $new_array[$ky[0]][] = $ky[1];
    $new_array[$ky[0]][] = $value;

}

print_r($new_array);