如果遇到条件,从多维数组中获取随机数组值

时间:2015-03-19 19:22:56

标签: php arrays multidimensional-array

我有一个像这样的数组:

$treadmills = [
    'bowflexseries3' => [
        'brand' => 'Bowflex',
        'description' => 'Bowflex Series 3',
        'image' => '/images/bowflex-series-3-150x150.jpg',
        'discontinued' => '0'
    ],
    'bowflexseries5' => [
        'brand' => 'Bowflex',
        'description' => 'Bowflex Series 5',
        'image' => '/images/bowflex-series-5-treadmill-review-150x150.jpg',
        'discontinued' => '1'
    ],
    'bowflextc10' => [
        'brand' => 'Bowflex',
        'description' => 'Bowflex Treadclimber TC10',
        'image' => '/images/bowflex-treadclimber-tc10-review-150x150.jpg',
        'discontinued' => '0'
    ]
];

如果停用= 0,我正试图随机抽出一台跑步机及其细节(品牌,描述,图片)。

这是我到目前为止所得到的:

function treadDetails($a) {
    global $treadmills;
    $treads = $treadmills;
    shuffle($treads);
    foreach( $treads as $brand=>$defaulttread2 ) {
        if($treads[$brand]['discontinued'] != '1') {
            return $defaulttread2[$a];
        }
    }
}

echo treadDetails('brand');
echo treadDetails('description');
echo treadDetails('image');

以上不太有效,因为它从不同的跑步机上随机抽取细节。我不想混合细节,所以如果它随机选择bowflextc10,那么它应该显示“Bowflex Treadclimber TC10”和“/images/bowflex-treadclimber-tc10-review-150x150.jpg”。

我尝试使用array_rand而不是shuffle,但它每次只拉出第一个跑步机和数组中的细节。

3 个答案:

答案 0 :(得分:0)

然后你需要完全拉出一个随机跑步机,而不是单独的属性。

foreach( $treads as $brand => $defaulttread2 ) {
    if($treads[$brand]['discontinued'] != '1') {
        return $defaulttread2;
    }
}

然后调用该函数一次,然后单独回显属性:

$treadmill = treadDetails();
echo $treadmill['brand'];
echo $treadmill['description'];
echo $treadmill['image'];

当然,您可能希望立即重命名您的函数,并删除$a参数。

如果是我,我会将方法重写为:

function randomTreadmill() {
    global $treadmills;

    // Filter out discontinued treadmills
    $filtered = array_filter($treadmills, function($treadmill) {
        return $treadmill['discontinued'] == 0;
    });

    // Shuffle, and return the first one
    shuffle($filtered);
    return array_shift($filtered);
}

工作示例:http://3v4l.org/mkcuK

答案 1 :(得分:0)

如果你需要从该数组中随机输入,请尝试:

$randomKey = array_rand($treads, 1);

echo $treads[$randomKey]['brand']; 

答案 2 :(得分:0)

不完全确定这是否属于你所追求的目标,但据我所知,这就是你想要的。

 function treadDetails() {
        global $treadmills;
        $treads = $treadmills;
        shuffle($treads);
        foreach( $treads as $tread ) {
            if($tread['discontinued'] != '1') {
                return $tread;
            }
        }
    }

product = treadDetails();

echo product['brand'];
echo product['description'];
echo product['image'];