简体   繁体   中英

Php shuffle part of associative array

I need to shuffle part of associative array. Example of array is below. Rules: shuffle needs to happen on same keys (ad-pre,ad-mid,ad-end). Order of key is always this (ad-pre,ad-mid,ad-end), however array may not always contain all keys (for example, there may not be ad-pre keys). So for example take all array items with keys 'ad-pre' and shuffle them and put back on same start, end index.

I ended up with this code, but its messy, and I am looking for a cleaner way. Also, next_key might not exist!

$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>';

I'm assuming here that your input array only contains these three ad_types, resp. that you want to shuffle in all of them, if there are more than those three, and there is nothing else in the input array that would need to be preserved as-is.

// 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);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM