douluan5444 2015-03-06 21:25
浏览 47
已采纳

使用数组作为函数参数php

I have an array that I would like to pass to a function as a parameter. These array values will be used to pull values out of another array and display them.

My Function:

function showTreadmills($listbrands) {
    global $treadmills;
    foreach( $treadmills as $brand=>&$features ) {
        if ($brand == $listbrands) { 
            return '<p>'.$features["description"].'</p>';
        }
    }
}

Treadmills Array:

$treadmills = [
    'bowflexseries3' => [
        'description' => 'Bowflex Series 3',
        'image' => '/images/bowflex-series-3-150x150.jpg',
        'url' => '/treadmills/bowflex/series-3',

    ],
    'solef85' => [
        'description' => 'Sole F85',
        'image' => '/images/sole-f85-150x150.jpg',
        'url' => '/treadmills/sole/f-85',
    ],
    'endurancet10hrc' => [
        'description' => 'Endurance T10HRC',
        'image' => '/images/endurance-t10hrc-150x150.jpg',
        'url' => '/treadmills/endurance/t10hrc',
    ]
];

Values that I'm trying to pull out of array in my function:

 <?php echo showTreadmills('bowflexseries3','solef85'); ?>

This only returns the first Description from the array, which is Bowflex Series 3. I'm trying to figure out how to get it to pull the description for bowflexseries3 and solef85. I'm sure it's a dumb oversight. Thanks in advance!

  • 写回答

3条回答 默认 最新

  • drgwsx8405 2015-03-06 21:35
    关注

    You're not passing an array to the function, you're passing two strings. You need to call array() to wrap an array around them:

    echo showTreadmills(array('bowflexseries3','solef85'));
    

    Then you need to change showTreadmills. You can't use == to compare a string to an array. It looks like you want to test whether the string is in the array, so it should be:

    if (in_array($brand, $listbrands))
    

    Or instead of looping through $treadmills and testing whether it's equal to one of $listbands, you could loop through $listbrands:

    $result = '';
    foreach ($listbrands as $brand) {
        if (isset($treadmills[$brand])) {
            $result .= '<p>'.$treadmills[$brand]["description"].'</p>';
        }
    }
    return $result;
    

    This is better, since it loops through the smaller array. And in_array() has to do a search, while accessing an associative array is just a hash lookup.

    Notice that you need to concatenate the results into a string during the loop. If you use return in the loop, you'll only return the first brand found.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(2条)

报告相同问题?

悬赏问题

  • ¥15 不是,这到底错哪儿了😭
  • ¥15 2020长安杯与连接网探
  • ¥15 关于#matlab#的问题:在模糊控制器中选出线路信息,在simulink中根据线路信息生成速度时间目标曲线(初速度为20m/s,15秒后减为0的速度时间图像)我想问线路信息是什么
  • ¥15 banner广告展示设置多少时间不怎么会消耗用户价值
  • ¥16 mybatis的代理对象无法通过@Autowired装填
  • ¥15 可见光定位matlab仿真
  • ¥15 arduino 四自由度机械臂
  • ¥15 wordpress 产品图片 GIF 没法显示
  • ¥15 求三国群英传pl国战时间的修改方法
  • ¥15 matlab代码代写,需写出详细代码,代价私