-1

我在洗牌时遇到了麻烦,希望有人可以指导我吗?

我有这个数组:(这个数组是从随机关联函数产生的)

Array
(
    [1] => Array
        (
            [boo] => hello
            [yeah] => world
        )    
)

我正在使用这个洗牌关联功能:

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

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

$test = shuffle_assoc($array);

echo "<pre>";
print_r($test);
echo "</pre>";

然后我得到这个:

Array
(
    [0] => Array
        (
            [boo] => hello // I'm trying to switch
            [yeah] => world // these two values
        )    
)

随机播放功能不会切换[boo]并且[yeah]

有人能帮我吗?

4

3 回答 3

0

I found a solution.

$test = shuffle_assoc(array_shift($array));

array_shift() brings the first element so it'll go from

Array
(
    [1] => Array
        (
            [boo] => hello
            [yeah] => world
        )    
)

to

Array
(
            [boo] => hello
            [yeah] => world
)

Notice how [1] is gone now

于 2012-12-11T06:21:12.290 回答
0

您需要跳过数组的第一级。

$array = array(1 => array('boo' => 'hello', 'yeah' => 'world', 'foo' => 'bar'));
function shuffle_assoc($list) {
    foreach ($list as $idx => &$sub_array) { // we actually loop over the numeric indexes since that's the first level
        $keys = array_keys($sub_array);
        $vals = array_values($sub_array);
        shuffle($vals);
        $sub_array = array_combine($keys, $vals);
    }
    return $list;
}
$new_arr = shuffle_assoc($array);
var_export($new_arr);

输出

array (
  1 => 
  array (
    'boo' => 'bar',
    'yeah' => 'hello',
    'foo' => 'world',
  ),
)
于 2012-12-11T06:03:16.790 回答
0

看起来你传入的数组实际上是一个数组数组,有 1 个元素。您应该在$array[1].

此外,在 中shuffle_assoc,该语句$random[] = $list[$key]不保留键值,因此结果数组将仅包含原始数组的值。将该行代码更改为$random[$key] = $list[$key]应该修复该功能。下面是一些对我有用的代码。

<?php
$array = array("boo" => "hello", "yeah" => "world");
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; 
}

$test = shuffle_assoc($array);

print_r($test);
?>
于 2012-12-11T06:06:09.890 回答