在数组中插入新元素


Insert new element in an array

已编辑

$queryPremium ="Select * from tablename where premium = 1 order by id desc";
$rowPremium = mysql_query($queryPremium);
$queryNotPremium ="Select * from tablename where premium = 0 order by id desc";
$rowNotPremium = mysql_query($queryNotPremium);

现在我想要一个单独的数组,其中rowNotPremium的顺序将被保持,$rowPremium将被随机插入$rowNotPremium中的2个数据之后或$rowNotPremium的3个数据之后。。。

如何做到这一点?

您可以这样做:

$newArray = $nonpremium + $premium

$newArray = array_merge($nonpremium, $premium)

很抱歉这里有任何不好的做法,如果你觉得可以编辑,请编辑它…

<?php
$arr_a = array('1','2','3','4','5','6');
$arr_b = array('apples','oranges','bananas','peaches'); 
// How many elements are in the array we are inserting into
$count = count($arr_a);
// What was the last insert position? Make sure the next will be greater than this
$prev = 0;
// Loop through each of our elements to insert
foreach($arr_b as $value)
{
    // Generate a random value, higher than the previous
    // random number but still less than count($arr_a)
    $rand = rand($prev, $count);
    // Store this as the previous value + 1
    $prev = $rand + 1;
    // Insert our value into $arr_a at the random position
    array_splice($arr_a, $rand, 0, $value);
}
echo "<pre>".print_r($arr_a, true)."</pre>"; 

使用array_splice((rand((数

$array1 = array( 1,2,3,4,5 );
$array2 = array( 6,7,8,9 ); 
array_splice( $array1, rand(0,count($array2)-1), 0, $array2 ); // splice in at random position