关联数组:保持为数组还是字符串?

时间:2017-03-05 14:13:11

标签: php arrays

我从我的数据库中获取此数组:

[0] => Array (
    [currency_id] => 1
    [currency_symbol] => USD
    )
[1] => Array (
    [currency_id] => 2
    [currency_symbol] => EUR
    )
[2] => Array (
    [currency_id] => 3
    [currency_symbol] => EGP
    )
[3] => Array (
    [currency_id] => 4
    [currency_symbol] => BTC
    )

现在我的PHP代码需要得到这样的数组:

$pdocrud->tableColFormatting("currency_id", "replace",array("3" =>"EGP","1" =>"USD"));

我是否需要将我的数组转换为以逗号分隔的字符串,或者我是否有更多"直接解决方案"? 感谢

2 个答案:

答案 0 :(得分:1)

这也可以。

$records = array(
    array(
        'currency_id' => 1,
        'currency_symbol' => 'USD',
    ),
    array(
        'currency_id' => 2,
        'currency_symbol' => 'EUR',
    ),

    array(
        'currency_id' => 3,
        'currency_symbol' => 'EGP',
    ),
    array(
        'currency_id' => 4,
        'currency_symbol' => 'BTC',
    )
);


$currency = array_column($records,'currency_symbol', 'currency_id');

答案 1 :(得分:0)

$arr = array(
    array(
        'currency_id' => 1,
        'currency_symbol' => 'USD'
    ),
    array(
        'currency_id' => 3,
        'currency_symbol' => 'EGP'
    )
);

print_r(
    array_combine(
         array_column($arr, 'currency_id'),
         array_column($arr, 'currency_symbol')
    )
);

给出

Array
(
    [1] => USD
    [3] => EGP
)