如何从数组值创建键?

时间:2019-07-03 04:28:40

标签: php

我有一个包含两个值的数组,但我需要较高的值作为较低值的键,例如name的值替换为value,还需要从数组中删除名称。

Array
(
    [0] => Array
        (
            [name] => firt_name
            [value] => Robin
        )

    [1] => Array
        (
            [name] => last_name
            [value] => Singh
        )

    [2] => Array
        (
            [name] => email
            [value] => 123@gmail.com
        )

    [3] => Array
        (
            [name] => password
            [value] => 12345
        )
)

这是代码

function key_replace($params = array())
{
    if (!empty($params)) {
        $array[] = array();
        foreach ($params as $key => $value) {
            $array[$value['name']] = $value['value'];
        }
        print_r($array);
    }
}

任何解决方案表示赞赏!

3 个答案:

答案 0 :(得分:2)

简单的foreach()将为您解决问题。

$result = [];
foreach($array as $k=>$v){
    $result[$v['name']] = $v['value'];
}
print_r($result);

工作演示: https://3v4l.org/hH39i

答案 1 :(得分:2)

另一种方法是使用array_columnarray_combine

array_combine(array_column($array, 'name'), array_column($array, 'value'));

https://3v4l.org/boAOI

答案 2 :(得分:0)

    $datas = $array = array
    (
        '0' => array
            (
                'name' => 'firt_name',
                'value' => 'Robin'
            )
,
        '1' => array
            (
                'name' => 'last_name',
                'value' => 'Singh'
            )
,
        '2' => array
            (
                'name' => 'email',
                'value' => '123@gmail.com'
            )
,
        '3' => array
            (
                'name' => 'password',
                'value' => '12345',
            )
,
        '4' => array
            (
                'name' => 'phone',
                'value' => 'skdsjdkdjskd'
            )
,
        '5' => Array
            (
                'name' => 'city',
                'value' => 'dskjdksjd'
            )
,
        '6' => Array
            (
                'name' => 'state',
                'value' => 'kjksdjskdsk'
            )

    );

 $array = '';
        foreach ($datas as $key => $value) {
            $array[$value['name']] = $value['value'];
        }

echo '<pre>';

print_r($array);

echo '</pre>';


Array
(
    [firt_name] => Robin
    [last_name] => Singh
    [email] => 123@gmail.com
    [password] => 12345
    [phone] => skdsjdkdjskd
    [city] => dskjdksjd
    [state] => kjksdjskdsk
)