PHP中如何随机打乱多维数组内[title][link]与[content][excerpt]分组
To achieve your goal of randomly shuffling the pairing between [title][link] groups and [content][excerpt] groups from your original array, follow these straightforward steps:
Step 1: Split the Original Array into Two Separate Groups
First, we'll extract the title-link pairs and excerpt-content pairs into their own distinct arrays. This lets us handle each group independently before recombining them randomly.
// Your original array (corrected to valid PHP syntax) $originalArray = [ [ 'title' => 'Title 0', 'link' => 'Link 0', 'excerpt' => 'Excerpt 0', 'content' => 'Content 0' ], [ 'title' => 'Title 1', 'link' => 'Link 1', 'excerpt' => 'Excerpt 1', 'content' => 'Content 1' ], [ 'title' => 'Title 2', 'link' => 'Link 2', 'excerpt' => 'Excerpt 2', 'content' => 'Content 2' ] ]; // Extract title-link pairs $titleLinkGroups = array_map(function($item) { return [ 'title' => $item['title'], 'link' => $item['link'] ]; }, $originalArray); // Extract excerpt-content pairs $excerptContentGroups = array_map(function($item) { return [ 'excerpt' => $item['excerpt'], 'content' => $item['content'] ]; }, $originalArray);
Step 2: Shuffle One of the Groups
Next, we shuffle either the title-link or excerpt-content array. Shuffling just one group ensures we get a random pairing without reusing any pairs (as long as both arrays are the same length, which they are in your case).
// Make a copy of the excerpt-content array to avoid modifying the original $shuffledExcerptContent = $excerptContentGroups; // Shuffle the copied array in-place shuffle($shuffledExcerptContent);
Step 3: Recombine the Shuffled Groups
Finally, merge each title-link pair with the corresponding (now shuffled) excerpt-content pair to create your final randomized array.
$finalShuffledArray = array_map(function($tl, $ec) { return array_merge($tl, $ec); }, $titleLinkGroups, $shuffledExcerptContent);
Example Output
After running this code, your $finalShuffledArray might look something like this (the exact pairing will vary each time due to randomness):
Array( [0] => Array( [title] => 'Title 0', [link] => 'Link 0', [excerpt] => 'Excerpt 2', [content] => 'Content 2' ), [1] => Array( [title] => 'Title 1', [link] => 'Link 1', [excerpt] => 'Excerpt 0', [content] => 'Content 0' ), [2] => Array( [title] => 'Title 2', [link] => 'Link 2', [excerpt] => 'Excerpt 1', [content] => 'Content 1' ) )
Key Notes
- No Duplicate Pairings: Since we're shuffling one array and merging index-by-index, each
title-linkpair will be matched with a uniqueexcerpt-contentpair (assuming your original array has no duplicate entries). - Preserve Original Data: By making a copy of the
excerpt-contentarray before shuffling, we keep your original array intact if you need it later. - Randomness: PHP's
shuffle()function uses a pseudo-random number generator, so you'll get a different result each time you run the code.
内容的提问来源于stack exchange,提问作者pattygeek

