我有这种数组
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'
)
)
如果洗牌整个数组内容我可以做到,但这种情况我仍然感到困惑,有人可以帮助我吗?
谢谢
肉饼
您可以使用array_column()
来获取值,然后随机播放键,最后使用相同的"随机"键更新内容:
$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
)
)