本文介绍了如何将数组的第一个值转换为键,第二个值转换为值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在做一些数组操作.

Hi I am working on some array operations.

我需要将数组的第一个值转换为键,并将数组的第二个值转换为值.

I need to convert first value of array as key and second value of array as value.

我有一个变量 $ testArray ,它存储如下所示的数组.

I have one variable $testArray which stores array like below.

 Array
(
    [0] => Array
        (
            [0] => Color
            [1] => White on Red
        )

    [1] => Array
        (
            [0] => Depicted Text
            [1] => EMPTY
        )

    [2] => Array
        (
            [0] => Depth [Nom]
            [1] => 0.004 in
        )

    [3] => Array
        (
            [0] => Language
            [1] => English
        )

    [4] => Array
        (
            [0] => Length [Nom]
            [1] => 10 in
        )

    [5] => Array
        (
            [0] => Material
            [1] => Adhesive Vinyl
        )

    [6] => Array
        (
            [0] => Mounting
            [1] => Surface
        )

    [7] => Array
        (
            [0] => Width [Nom]
            [1] => 14 in
        )

    [8] => Array
        (
            [0] => Wt.
            [1] => 0.056 lb
        )

)

预期输出:

    Array
(
    [0] => Array
        (
            [Color] => White on Red
        )

    [1] => Array
        (
            [Depicted Text] => EMPTY
        )

    [2] => Array
        (
            [Depth [Nom]] => 0.004 in
        )

    [3] => Array
        (
            [Language] => English
        )

    [4] => Array
        (
            [Length [Nom]] => 10 in
        )

    [5] => Array
        (
            [Material] => Adhesive Vinyl
        )

    [6] => Array
        (
            [Mounting] => Surface
        )

    [7] => Array
        (
            [Width [Nom]] => 14 in
        )

    [8] => Array
        (
            [Wt.] => 0.056 lb
        )

)

我已经尝试过使用数组函数array_keys和array_values,但无法正常工作

推荐答案

使用 array_map 函数:

$result = array_map(function($v){
    return [$v[0] => $v[1]];
}, $testArray);

这篇关于如何将数组的第一个值转换为键,第二个值转换为值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-10 14:01