Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.1k views
in Technique[技术] by (71.8m points)

php - How to convert array first value as key and second value as value

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.

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
        )

)

Expected output :

    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
        )

)

I have already tried with array function array_keys and array_values but it won't working

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Simple solution using array_map function:

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...