1

I have the following multidimensional array that is obtained through an API.

$exchangeID = array(
    0 => array(
        'id' => 'vcxz', 
        'currency' => 'GBP',
        ),
    1 => array(
        'id' => 'mnbv',
        'currency' => 'EUR',
        ),
    2 => array(
        'id' => 'lkjh',
        'currency' => 'USD', 
        ),
    3 => array(
        'id' => 'poiuy',
        'currency' => 'KRN',
        ),
    );

I would like to obtain the id of USD which is lkjh. I know this can be obtained by simply doing $exchangeID[2]['id']. The problem is that the array is dynamic. For example when it is loaded the first subarray may be EUR instead of GBP, and the third subarray may be KRN instead of USD.

Basically, what I have in mind is to look for the subarray where there is the currency first, then accordingly find the corresponding id. E.g. if I want to find EUR. First I find the EUR, then get 'mnbv'.

I tried this $key = array_search('USD', array_column($exchangeID, 'currency')); but I got the following error in my error_log PHP Fatal error: Call to undefined function array_column() to get at least the array number e.g. in this case 2.

2
  • 3
    It seems that you are using a PHP version lower than 5.5 - In this case you could check this implementation github.com/ramsey/array_column/blob/master/src/array_column.php if you want to avoid the PHP fatal error Commented Sep 5, 2015 at 23:33
  • does my answer work? if so let me know :) Commented Sep 5, 2015 at 23:45

5 Answers 5

2

You can simply filter your array, like this:

$usd_exchanges = array_filter($exchangeID, function($row) {
  return $row['currency'] == "USD";
}));
var_dump($usd_exchanges[0]);

You can also return the first element of the filter, using the current method:

$usd_exchange = current(array_filter($exchangeID, function($row) {
  return $row['currency'] == "USD";
})));
var_dump($usd_exchange);
Sign up to request clarification or add additional context in comments.

2 Comments

Plus for array_filter + current. Might want to add obtaining the id only (not the entire data-set).
this will work, but might waste time after the key has been found - this will check every record in the array, and continue after the key has been found :o until the list is exhausted
1

Try this:

foreach ($exchangeID as $key => $arr)
  if($arr['currency'] == 'USD')
    echo $key;

It is possible to use following custom function to get the key:

echo getKeyRecursive('USD', $exchangeID);
function getKeyRecursive($needle, $haystack, $strict = false)
{
  foreach ($haystack as $key => $item){
     if(($strict ? $item === $needle : $item == $needle) || (is_array($item) && getKeyRecursive($needle, $item, $strict))) return $key;
  }
  return false;
}

Comments

1
foreach($exchangeID as $key=>$value)
    {
        if($exchangeID[$key]['currency']=='USD'){
            $usdId=$exchangeID[$key]['id'];
      break;
        }
    }
//echo $usdId; 
//Result:ikjh

3 Comments

Minus for using echo.
adding a break; will make it faster - the current code keeps looking until the list is exhausted, while it should stop asap when the key has been found
Removed echo, added break.happy? Hehe :-)
0
<?php
$exchangeID = array(
    0 => array(
        'id' => 'vcxz', 
        'currency' => 'GBP',
        ),
    1 => array(
        'id' => 'mnbv',
        'currency' => 'EUR',
        ),
    2 => array(
        'id' => 'lkjh',
        'currency' => 'USD', 
        ),
    3 => array(
        'id' => 'poiuy',
        'currency' => 'KRN',
        ),
    );
$db=new PDO('sqlite::memory:','','',array(PDO::ATTR_EMULATE_PREPARES => false, PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION));
$db->query('CREATE TABLE `troll` (`dbid` TEXT, `dbcurrency` TEXT);');
$stm=$db->prepare("INSERT INTO `troll` (`dbid`,`dbcurrency`) VALUES(:id,:currency);");
array_walk($exchangeID,function($arr)use($stm){$stm->execute($arr);});
$res=$db->query("SELECT `dbid` AS `id` FROM `troll` WHERE `dbcurrency` = ".$db->quote('USD').' LIMIT 1');

$id=$res->fetch(PDO::FETCH_ASSOC);
$id=$id['id'];
var_dump($id);

see working example here http://codepad.viper-7.com/1lg2Gj

Comments

0

Try this if this works:

  foreach($exchangeID as $key => $val)
  {
      if(array_key_exists('currency', $val))
        if($val['currency'] == 'USD'){
          echo $val['id'];
          echo $val['currency'];
        elseif($val['currency'] == 'GBP'){a1
           echo $val['id'];
          echo $val['currency']);
       elseif($val['currency'] == 'EUR'){
          echo $val['id'];
         echo $val['currency'];
         }else{
          echo $val['id'];
         echo $val['currency'];
       }
    }
  }

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.