Piotr
Piotr

Reputation: 29

PHP get value from array for id

I have array

array (size=2)
  0 => 
    array (size=1)
      'Product' => 
        array (size=2)
          'id' => string '109' (length=3)
          'name' => string 'product1' (length=2)
  1 => 
    array (size=1)
      'Product' => 
        array (size=2)
          'id' => string '110' (length=3)
          'name' => string 'product2' (length=2)

Is it possible to get name for id? Example, I have id 109 and want get name product1.

Upvotes: 1

Views: 7365

Answers (2)

TiMESPLiNTER
TiMESPLiNTER

Reputation: 5889

Try this to find the product name:

function getProductNameById($products, $productId) {
    foreach($products as $p) {
        if($p['Product']['id'] == $productId) {
            return $p['Product']['name'];
        }
    }
}

Where $products is your array with your products in it and $productId the id of the product for which you want to find its name.

Upvotes: 3

Vit Kos
Vit Kos

Reputation: 5755

You can use something like this

function getName($id, $array)
{
  foreach ($array as $product)
  {
    if ($product['Product']['id'] == $id)
      return $product['Product']['name'];
  }
}

Upvotes: 1

Related Questions