关联数组的Php随机播放部分

问题描述 投票:-1回答:1

我需要改组关联数组的一部分。数组的示例如下。规则:随机播放需要在相同的键(ad-pre,ad-mid,ad-end)上进行。键的顺序始终是此顺序(ad-pre,ad-mid,ad-end),但是数组可能并不总是包含所有键(例如,可能没有ad-pre键)。因此,例如,使用键为“ ad-pre”的所有数组项将它们洗牌,然后放回相同的开始索引,结束索引。

我最终得到了这段代码,但是它很乱,我正在寻找一种更简洁的方法。另外,next_key可能不存在!

$data = array(
  array(
    "ad_type"=> "ad-pre",
    "type"=> "a1"
  ),
  array(
    "ad_type"=> "ad-pre",
    "type"=> "a2"
  ),
  array(
    "ad_type"=> "ad-mid",
    "type"=> "b1"
  ),
  array(
    "ad_type"=> "ad-mid",
    "type"=> "b2"
  ),
  array(
    "ad_type"=> "ad-mid",
    "type"=> "b3"
  ),
  array(
    "ad_type"=> "ad-end",
    "type"=> "c1"
    )
);
echo '<pre>';
var_dump($data);
echo '</pre>';

$sub = array();
$index = 0;
$len = 0;
$start;
$key = 'ad-mid';
$next_key = 'ad-end';
foreach($data as $row){
    if($row['ad_type'] == $key){
        if(!isset($start))$start = $index;
        $len++;
    }
    else if($row['ad_type'] == $next_key){//I want to break by next key (so it doesnt loop all array), but this is not good because this key may not exist!
        break;
    }
    $index++;
}

var_dump($start,$len);

$sub = array_splice($data, $start, $len);
shuffle($sub);
array_splice($data, $start,0, $sub);

echo '<pre>';
var_dump($data);
echo '</pre>';
php associative-array shuffle
1个回答
0
投票

我在这里假设您的输入数组only分别包含这三种ad_type。您想在其中的[[all中进行混洗,如果有三个以上,并且输入数组中没有其他需要保留的原样。

// group items in a helper array, under the ad_type $helper = []; foreach($data as $item) { $helper[$item['ad_type']][] = $item; } // loop over the grouped ad_type arrays, shuffle their items, add shuffled items to result array $result = []; foreach($helper as $items) { shuffle($items); $result = array_merge($result, $items); } var_dump($result);
© www.soinside.com 2019 - 2024. All rights reserved.