PHP How to mixed the two FOREACH data random?
I tried this method, but it caused Fatal error: Allowed memory size of 134217728 bytes exhausted (tried to allocate 42 bytes) in E:\www\json_example\4.php on line 170
the line in foreach foreach($data_b as $b)
$arr[] =
.
so in addition to the this method, is there any easy way can mixed the two FOREACH data random? less cost memory. (Not quite necessarily sort by title) Thanks.
foreach($data_a as $a){
//$a['title'];
//$a['content'];
$arr[] = array('title' => html_entity_decode($a['title'], ENT_QUOTES, 'UTF-8'),'content' => html_entity_decode($a['content'], ENT_QUOTES, 'UTF-8'));
}
foreach($data_b as $b){
//$b['title'];
//$b['content'];
$arr[] = array('title' => html_entity_decode($b['title'], ENT_QUOTES, 'UTF-8'),'content' => html_entity_decode($b['content'], ENT_QUOTES, 'UTF-8'));
}
function cmp($aa, $bb)
{
$t1 = $aa['title'];
$t2 = $bb['title'];
if ($t1 == $t2) return 0;
return $t1 < $t2 ? -1 : 1;
}
usort($arr, 'cmp');
foreach ($arr as $item){
echo $item['title'];
echo $item['content']开发者_开发百科;
}
so in addition to the this method, is there any easy way can mixed the two FOREACH data random? less cost memory. (Not quite necessarily sort by title)
Apparently, you have a huge dataset, as you're reaching the limit of 134217728 bytes (which is ~134MB). The main question is; where are you getting this data from? Is it from two different data sources, or one source (e.g. a database)? In my experience, people tend to solve problems like this in PHP, while it would be easily solved with a SELECT ... UNION SELECT ... ORDER BY RANDOM( );
Try to free memory as soon as you don't need it anymore:
function _h_dec($val) {
return html_entity_decode($val, ENT_QUOTES, 'UTF-8');
}
foreach ($data_a as $key => $a) {
$arr[] = array('title' => _h_dec($a['title']), 'content' => _h_dec($a['content']));
unset($data_a[$key]);
}
unset($data_a);
foreach ($data_b as $key => $b) {
$arr[] = array('title' => _h_dec($b['title']), 'content' => _h_dec($b['content']));
unset($data_b[$key]);
}
unset($data_b);
function cmp($aa, $bb) {
$t1 = $aa['title'];
$t2 = $bb['title'];
if ($t1 == $t2)
return 0;
return $t1 < $t2 ? -1 : 1;
}
usort($arr, 'cmp');
foreach ($arr as $item) {
echo $item['title'];
echo $item['content'];
}
hi have you tried this: Php's shuffle. http://php.net/manual/en/function.shuffle.php
精彩评论