获取子数组的第一个元素作为其键

时间:2018-01-06 12:11:11

标签: php arrays transform associative-array associative

我正在寻找一种简单的方法来转换关联数组的键。 我希望子数组的键是自己的第一个值。 有可能改变这个:

Array
(
[0] => Array
    (
        [symbol] => ETHBTC
        [status] => TRADING
    )
[1] => Array
    (
        [symbol] => LTCBTC
        [status] => TRADING
    )
)

到此:

Array
(
[ETHBTC] => Array
    (
        [status] => TRADING
    )
[LTCBTC] => Array
    (
        [status] => TRADING
    )
)

2 个答案:

答案 0 :(得分:1)

这并没有完全给出你的确切输出,但它可能是你的...

$data = Array
(
        Array
        (
                'symbol' => 'ETHBTC',
                'status' => 'TRADING'
                ),
        Array
        (
                'symbol' => 'LTCBTC',
                'status' => 'TRADING2'
                )
        );

$data = array_column($data, null, 'symbol');
print_r($data);
echo $data['LTCBTC']['status'];

...给出

Array
(
    [ETHBTC] => Array
        (
            [symbol] => ETHBTC
            [status] => TRADING
        )

    [LTCBTC] => Array
        (
            [symbol] => LTCBTC
            [status] => TRADING2
        )

)
TRADING2

答案 1 :(得分:0)

$array = Array
( Array
    (
        "symbol" => "ETHBTC",
        "status" => "TRADING"
    ),
Array
    (
        "symbol" => "LTCBTC",
        "status" => "TRADING"
    )
);

$append = [];

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