在PHP中转换数组结构 [英] Transform array-structure in php

查看:48
本文介绍了在PHP中转换数组结构的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果我有一个来自这样的数据库的数组:

If I have an array which comes from a database like this:

$array = [  
    'dataset_1' => [
        'some' => '...',
        'array' => '...',
    ],  
    'dataset_2' => [
        'some' => '...',
        'thing' => '...',
        'else' => '...', 
    ] 
];

...如何将这个数组转换为另一个结构,如:

... how can I transform this array to another structure like:

$array = [ 
    'whatever' => [
        'some' =>'...',
        'array' => '...',
        'some' =>'...',
        'thing' => '...',
        'else' => '...',
    ] 
];

我考虑过OptionResolver,但是我不知道是否有人可以给我提示或示例?

I thought about OptionResolver, but I have no idea so if anyone can give me a hint or an example?

推荐答案

您可以使用 array_merge 以及

You can do it using array_merge along with ..., in case you have an uknown number of datasets, to get your result. Beware though, as you have duplicate keys in your arrays which means that you will lose all duplicate keys but one. Consider using unique keys:

$input = array(  
   'dataset_1'=>[
      'some' =>'...',
      'array' => '...', ],  
   'dataset_2'=>[
      'some' =>'...',
      'thing' => '...',
      'else' => '...', 
   ] 
);


$output['whatever'] = array_merge(...array_values($input));
print_r($output);

输出:

Array
(
    [whatever] => Array
        (
            [some] => ...
            [array] => ...
            [thing] => ...
            [else] => ...
        )

)

这篇关于在PHP中转换数组结构的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆