Home > Backend Development > PHP Tutorial > PHP code for disrupting arrays, two-dimensional arrays, and multi-dimensional arrays

PHP code for disrupting arrays, two-dimensional arrays, and multi-dimensional arrays

不言
Release: 2023-03-30 15:32:01
Original
1705 people have browsed it

The following is a simple example of how to use PHP to disrupt an array, a two-dimensional array, and a multi-dimensional array. The content is quite good, so I will share it with you now and give it as a reference.

The shuffle function in php can only shuffle one-dimensional arrays. Is there any way to shuffle multi-dimensional arrays quickly and conveniently? The manual provides

<?php 
function shuffle_assoc($list) { 
 if (!is_array($list)) return $list; 
 $keys = array_keys($list); 
 shuffle($keys); 
 $random = array(); 
 foreach ($keys as $key) 
  $random[$key] = $list[$key]; 
 return $random; 
} 
?>
Copy after login

The above is for two-dimensional arrays!

The following shuffle method for multi-dimensional arrays? As convenient and fast as possible:

<?php 
function shuffle_assoc($list) { 
if (!is_array($list)) return $list; 

$keys = array_keys($list); 
shuffle($keys); 
$random = array(); 
foreach ($keys as $key) 
$random[$key] = shuffle_assoc($list[$key]); 

return $random; 
} 
?>
Copy after login

The following functions are also from the PHP manual, which can scramble multi-dimensional arrays:

/**
* Shuffles an associative array recursive
* 
* @param array $array
* @return array
*
*/

function rec_assoc_shuffle($array)
{
 $ary_keys = array_keys($array);
 $ary_values = array_values($array);
 shuffle($ary_values);
 foreach($ary_keys as $key => $value) {
  if (is_array($ary_values[$key]) AND $ary_values[$key] != NULL) {
   $ary_values[$key] = rec_assoc_shuffle($ary_values[$key]);
  }
  $new[$value] = $ary_values[$key];
 }
 return $new;
}
Copy after login

The above is the entire content of this article. I hope it will be helpful to everyone's learning. More For more related content, please pay attention to the PHP Chinese website!

Related recommendations:

php implementation method of merging arrays and retaining key values

The above is the detailed content of PHP code for disrupting arrays, two-dimensional arrays, and multi-dimensional arrays. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
php
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template