我有这种数组
Array(
[0]=>Array(
[title] => 'Title 0'
[link] => 'Link 0'
[excerpt] => 'Excerpt 0'
[content] => 'Content 0'
)
[1]=>Array(
[title] => 'Title 1'
[link] => 'Link 1'
[excerpt] => 'Excerpt 1'
[content] => 'Content 1'
)
[2]=>Array(
[title] => 'Title 2'
[link] => 'Link 2'
[excerpt] => 'Excerpt 2'
[content] => 'Content 2'
)
)
如何在[内容],[摘录]和[标题],[链接]之间进行随机播放 所以基本上它会看起来像这样类似
Array(
[0]=>Array(
[title] => 'Title 0'
[link] => 'Link 0'
[excerpt] => 'Excerpt 1'
[content] => 'Content 1'
)
[1]=>Array(
[title] => 'Title 1'
[link] => 'Link 1'
[excerpt] => 'Excerpt 2'
[content] => 'Content 2'
)
[2]=>Array(
[title] => 'Title 2'
[link] => 'Link 2'
[excerpt] => 'Excerpt 0'
[content] => 'Content 0'
)
)
如果将整个数组内容改组,我可以这样做,但这种情况我仍然感到困惑,任何人都可以帮助我吗?
谢谢
小馅饼
答案 0 :(得分:2)
您可以使用array_column()
来获取值,然后将密钥随机播放,最后使用相同的" shuffled"更新内容。键:
$array = array(
array(
'title' => 'Title 0',
'link' => 'Link 0',
'excerpt' => 'Excerpt 0',
'content' => 'Content 0'
),
array(
'title' => 'Title 1',
'link' => 'Link 1',
'excerpt' => 'Excerpt 1',
'content' => 'Content 1'
),
array(
'title' => 'Title 2',
'link' => 'Link 2',
'excerpt' => 'Excerpt 2',
'content' => 'Content 2'
)
);
// get data
$excerpts = array_column($array, 'excerpt');
$contents = array_column($array, 'content');
// get keys and shuffle them
$keys = array_keys($array);
shuffle($keys);
// iterate over array (and pass $values as reference)
foreach ($array as $key => &$values) {
// get the new shuffled key
$rand_key = $keys[$key];
// update content
$values['excerpt'] = $excerpts[$rand_key];
$values['content'] = $contents[$rand_key];
}
print_r($array);
可以输出:
Array
(
[0] => Array
(
[title] => Title 0
[link] => Link 0
[excerpt] => Excerpt 0
[content] => Content 0
)
[1] => Array
(
[title] => Title 1
[link] => Link 1
[excerpt] => Excerpt 2
[content] => Content 2
)
[2] => Array
(
[title] => Title 2
[link] => Link 2
[excerpt] => Excerpt 1
[content] => Content 1
)
)