-2

I have an array of cryptocoin rates. The array is looking as:

$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 ) )

I get results using $array[1]['rate'];

But i want to get result by [code] .

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

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

How i can get the rate using currency code e.g USD

2 Answers2

1

You can loop the array and build a new associative array to use in the rest of the project.

$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


Another option is to use array_column and array_combine to do it without loops.

$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'];
Andreas
  • 23,610
  • 6
  • 30
  • 62
0

You could use array_reduce and set the key to the value of code in the callback function:

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

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

Demo

The fourth bird
  • 154,723
  • 16
  • 55
  • 70