1

Given the following array and a given id, how can I return the corresponding elem? For instance, given id=6, it should return goodby. The id values are the PKs from a database, thus will always be unique.

Obviously, I could just iterate over the first array, check the values, and break and return the elem upon match, but I expect there is a much more elegant way to do this.

array(
    array('id'=>2,'elem'=>"hello"),
    array('id'=>6,'elem'=>"goodby"),
    array('id'=>8,'elem'=>"goodnight")
);
user1032531
  • 24,767
  • 68
  • 217
  • 387
  • possible duplicate of [PHP Multidimensional Array Searching (Find key by specific value)](http://stackoverflow.com/questions/8102221/php-multidimensional-array-searching-find-key-by-specific-value) – user2226755 Jul 10 '14 at 16:01
  • His second paragraph states that he is looking for a different way to do this, rather than wrapping a loop in a function, so I don't think it would be a duplicate. – Brett Santore Jul 10 '14 at 16:04

4 Answers4

1

A basic alternative to consider would be to collect the columns with array_column (indexed by the id column) and then dereferencing the array to access the passed index value $id, something like:

$myArray = array(
    array('id'=>2,'elem'=>"hello"),
    array('id'=>6,'elem'=>"goodby"),
    array('id'=>8,'elem'=>"goodnight")
);

function getValue($id, $a)
{
    return array_column($a, 'elem', 'id')[$id];
}

var_dump(getValue(6, $myArray));

Enhancing the proof to get more control:

function getValueAlternative($where, $get, $fromSource)
{
    $where = explode("=", $where);

    return array_column($fromSource, $get, $where[0])[$where[1]];
}

var_dump(getValueAlternative("id=2", "elem",  $myArray));
var_dump(getValueAlternative("elem=hello", "id",  $myArray));
ilpaijin
  • 3,645
  • 2
  • 23
  • 26
0

Why don't you use the following structure?:

array(
    2 => array('elem'=>"hello", ...),
    6 => array('elem'=>"goodby", ...),
    8 => array('elem'=>"goodnight", ...)
);

Then you could access them like:

$array[$id];

You told that you've used PDOStatement::fetchAll() to obtain your array. You can tell fetchAll() to return a structure like I've suggested, you need to use the fetch mode PDO::FETCH_GROUP:

$pdo->query('SELECT * FROM table')->fetchAll(PDO::FETCH_GROUP);

Well defined data structures are the essential basics of a good program. In your case an associative array having the ids as their keys and the whole records as the value portion,will be better than a numeric array as it allows you to perform fast, id based access. Of course you have to pay for this - with a little more memory.

hek2mgl
  • 152,036
  • 28
  • 249
  • 266
  • 1
    Was wondering the same thing. Though suspected it may be (based on the id) a returned array for somewhere, though they could still edit the initial return. – user1947561 Jul 10 '14 at 15:56
  • Because the array doesn't have that structure and the data is returned using fetchall. – user1032531 Jul 10 '14 at 15:56
  • You can customize the style how fetchAll will return the array.. I think to remember that *their is something*. If not, then simply use `fetch()`.. `fetchAll()` makes no sense at all in the most cases. – hek2mgl Jul 10 '14 at 16:00
  • @hek2mgl I didn't know I could style fetchAll to put the PK as the array key. Do you know for sure whether it is possible? Thanks – user1032531 Jul 10 '14 at 16:05
  • @user1032531 Its `PDO::FETCH_GROUP` – hek2mgl Jul 10 '14 at 16:18
  • @BrettSantore Having a scalar value will in most cases not fit as you will obtain multiple values per row. However, the id itself does not need to be part of that array again, of course. This is exactly what `PDO::FETCH_GROUP` does. – hek2mgl Jul 10 '14 at 16:22
0

You could use the array_search PHP function:

    /**
     * @param array $array
     * @param int $id
     * @return string|null
     */
    function getElem(array $array, $id) {
        foreach($array as $subArr) {
            if(($key = array_search($id, $subArr, true)) !== false) {
                if(strcmp($key, "id") === 0) {
                    return $subArr['elem'];
                }
            }
        }
        return null;
    }
    $array = array(
            array('id'=>2,'elem'=>"hello"),
            array('id'=>6,'elem'=>"goodby"),
            array('id'=>8,'elem'=>"goodnight")
        );
    echo getElem($array, 6);
james
  • 26,141
  • 19
  • 95
  • 113
0

See this :

myfunction($products, $needle)
{
   foreach($products as $key => $product)
   {
      if ( $product['id'] === $needle )
         return $key;
   }
   return false;
}

Similar : PHP Multidimensional Array Searching (Find key by specific value)

Community
  • 1
  • 1
user2226755
  • 12,494
  • 5
  • 50
  • 73