0

我有以下功能,我在数组中有品牌信息。当我将品牌名称传递给这个函数时,我应该得到包含这些信息的数组。

function brand_info($brand)
{
    $brands_list=array ( 
    'lg'=>
    array(
    'name'           => 'LG Phone Company',
    'country'        =>  'country',
    'founded_year'   =>  '2001'
    ),
    'nokia'=>
    array(
    'name'           => 'Nokia Phone Company',
    'country'        =>  'country',
    'founded_year'   =>  '2001'
    )
    );


    if(in_array($brand,$brands_list))
    {
        // return array containg company info
    }
}

这应该返回一个数组,我可以通过它显示这些信息。

$brand_info=brand_info($brand_name);
echo $brand_info['name'];

最好的方法是什么?

4

4 回答 4

3

如果您要传递品牌名称,那么这就足够了:

function brand_info($brand)
{
    $brands_list=array ( 
    'lg'=>
    array(
    'name'           => 'LG Phone Company',
    'country'        =>  'country',
    'founded_year'   =>  '2001'
    ),
    'Nokia'=>
    array(
    'name'           => 'Nokia Phone Company',
    'country'        =>  'country',
    'founded_year'   =>  '2001'
    )
    );

    if (array_key_exists($brand,$brands_list)) {
      return $brands_list[$brand];
    } else {
      return false;
    }
}

$brandinfo = brand_info('Nokia');
echo $brandinfo['name']; // will print "Nokia Phone Company"
于 2012-05-18T10:19:06.560 回答
1

可能看起来微不足道,但...

return $brands_list[$brand]
于 2012-05-18T10:19:52.073 回答
1
function brand_info($brand)
{
    $brands_list=array ( 
    'lg'=>
    array(
    'name'           => 'LG Phone Company',
    'country'        =>  'country',
    'founded_year'   =>  '2001'
    ),
    'nokia'=>
    array(
    'name'           => 'Nokia Phone Company',
    'country'        =>  'country',
    'founded_year'   =>  '2001'
    )
    );


    if(in_array($brand,$brands_list))
    {
        return $brand_list[$brand];
    }else{
        return null;
    }
}

进而

$info = brand_info($my_brand);
if(!is_null($info)){ echo $info['name']; }
于 2012-05-18T10:23:29.787 回答
1
function brand_info($brand) {
    $brands_list=array (
        'lg'=>
            array(
                    'name'           => 'LG Phone Company',
                    'country'        =>  'country',
                    'founded_year'   =>  '2001'
            ),
        'Nokia'=>
            array(
                    'name'           => 'Nokia Phone Company',
                    'country'        =>  'country',
                    'founded_year'   =>  '2001'
            )
    );


    foreach ($brands_list as $brandname=>$info) {
        if($brandname==$brand) {
            return $info;
        }
    }
    return array();
}
于 2012-05-18T10:32:00.553 回答