我有一系列的加密币率。 该阵列看起来像:
$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
答案 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
另一种选择是使用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