从具有相同键名的php数组中获取值

a quick answer about how to get the value (and pass it in a php variable) from an array:

i've this array:

$array = array(
            array('name' => 'infotel', 'value' => '+39080123456' ), 
            array('name' => 'location', 'value' => 'Bari')
            );

I need to pass the "value" of "infotel" in a $telephone variable, and the "value" of "location" in a $city variable.

how can i solve this trouble? thanks

you can create a function for that.

function custom_search($search_for='',$search_in=array())
{
  if($search_for=='' OR empty($search_in)) return '';
    foreach($search_in as $val)
    {
       if($val['name']==$search_for) {return $val['value'];}
    }
  return '';
}
$telephone=custom_search("infotel",$array);
$telephone='';
$location='';
foreach($array as $k=>$v)
{
   if($v['name']=="infotel") 
   {
     $telephone=$v['value'];
     break;
   }
   if($v['name']=="location") 
   {
     $location=$v['value'];
     break;
   }
}
echo $telephone; 
echo $location;

If you have only this array, use:

$tel = $array[0]['value'];
$loc = $array[1]['value'];
$array = array(
    array('name' => 'infotel', 'value' => '+39080123456' ),
    array('name' => 'location', 'value' => 'Bari')
);

$telephone = $array[0]['value'];
$city = $array[1]['value'];
echo $telephone;

echo $city;

I might do it using the new array_column()(requires PHP >= 5.5) and array_walk().

The good 'ol foreach loop should be fine, or you could just pull them out directly assuming you know what is in the array all the time. But here's something I think is a little fancier ;) ...

$arr = array_column($array, 'value', 'name');

array_walk($arr, function(&$v, $k) use (&$telephone, &$city){
    if ($k == 'infotel') $telephone = $v;
    elseif ($k == 'location') $city = $v;
});

echo $telephone; //+39080123456
echo $city;      //Bari

See Demo - updated updated updated

You can get your desire result by using this code. you need not to worry about array keys. but last key will replace your location and telephone value.

$array = array(
            array('name' => 'infotel', 'value' => '+39080123456' ), 
            array('name' => 'location', 'value' => 'Bari')
            );
$key1 = '';
$key2 = '';
foreach($array as $k => $a){
    if(array_search('infotel', $a) != false){
        $key1 = $k;
    }
    if(array_search('location', $a) != false){
        $key2 = $k;
    }
}
echo 'telephone = '.$array[$key1]['value'];
echo 'location = '.$array[$key2]['value'];