首页 > 解决方案 > 如何将第一个值转换为数组名称php的键

问题描述

如何将第一个值转换为数组和 php 的键。嗨,我正在处理一些数组操作。以下是我拥有的数组:

$data= array
(
    array('city', 'california','big city'),
    array('address', 'this is','address', 'zzz'),
    array('something', 'item 3','details 3'),
);

Array
(
    [0] => Array
        (
            [0] => city
            [1] => california
            [2] => big city
        )
    [1] => Array
        (
            [0] => address
            [1] => this is
            [2] => address
            [3] => zzz
    [2] => Array
        (
            [0] => something
            [1] => item 3
            [2] => details 3
        )
        ..........
)

我期待这个结果:

Array
(
    [city] => Array
        (
            [0] => city
            [1] => california
            [2] => big city
        )
    [address] => Array
        (
            [0] => address
            [1] => this is
            [2] => address
            [3] => zzz
    [something] => Array
        (
            [0] => something
            [1] => item 3
            [2] => details 3
        )
        ..............
)

上面提到的是结果。我已经尝试过使用数组函数 array_keys 和 array_values 但它不起作用。帮帮我

标签: phparrayskey

解决方案


尝试forEach

 $data= array
(
    array('city', 'california','big city'),
    array('address', 'this is','address', 'zzz'),
    array('something', 'item 3','details 3'),
);
 $res=[];
foreach($data as $val){
    $res[$val[0]] = $val;
}
print_r($res);

推荐阅读