如果我们有数组索引的概念,使用array_column函数如何从数组中获取记录?

时间:2018-05-19 07:56:12

标签: php arrays associative-array

我有一系列的加密币率。 该阵列看起来像:

$array = Array ( [0] => Array ( [code] => BTC [name] => Bitcoin [rate] => 1 )
 [1] => Array ( [code] => BCH [name] => Bitcoin Cash [rate] => 7.06364 )
 [2] => Array ( [code] => USD [name] => US Dollar [rate] => 8185.84 ) )

我使用$array[1]['rate'];

获得结果

但我想通过[代码]获得结果。

$array['USD']['rate']

$array['BCH']['rate']

我如何使用货币代码获得费率,例如 USD

2 个答案:

答案 0 :(得分:1)

您可以循环数组并构建一个新的关联数组,以便在项目的其余部分中使用。

$array = Array( 0 => Array( "code" => "BTC", "name" => "Bitcoin", "rate" => 1 ),
 "1" => Array ( "code" => "BCH", "name" => "Bitcoin Cash", "rate" => 7.06364 ),
 "2" => Array ( "code" => "USD", "name" => "US Dollar", "rate" => 8185.84 ) );

 foreach($array as $val){
     $rates[$val["code"]] = $val;
 }

 echo $rates['USD']['rate']; // 8185.84

https://3v4l.org/0qs0n

另一种选择是使用array_column和array_combine来做到没有循环。

$array = Array( 0 => Array( "code" => "BTC", "name" => "Bitcoin", "rate" => 1 ),
 "1" => Array ( "code" => "BCH", "name" => "Bitcoin Cash", "rate" => 7.06364 ),
 "2" => Array ( "code" => "USD", "name" => "US Dollar", "rate" => 8185.84 ) );

 $keys = array_column($array, "code");
 $rates = array_combine($keys, $array);

 echo $rates['USD']['rate'];

答案 1 :(得分:0)

您可以使用array_reduce并在回调函数中将密钥设置为code的值:

$array = array_reduce($array, function($carry, $item) {
    $carry[$item["code"]] = $item;
    return $carry;
});

echo $array["USD"]["rate"]; //8185.84

Demo