php - How to dynamically combine two arrays while making sure that they're evenly distributed? -
i'm trying combine 2 arrays have second array evenly distributed in first array. i'm open not merging them if there's nice loop solution i'm trying solve build new array.
array 1 looks this:
$array_1 = array( array('cat'), array('cat'), array('cat'), array('cat'), array('cat'), array('cat'), array('cat'), array('cat'), array('cat'), array('cat'), array('cat'), array('cat'), array('cat'), array('cat'), array('cat'), array('cat'), array('cat'), array('cat'), array('cat'), array('cat'), array('cat'), array('cat'), array('cat'), array('cat'), array('cat'), array('cat'), array('cat') );
array 2 looks like:
$array_2 = array( array('dog'), array('dog'), array('dog'), array('dog') );
i want merge these one. kicker want evenly space out array 2 in array 1. illustrate question, like:
$array_1 = array( array('cat'), array('cat'), array('cat'), array('cat'), array('cat'), array('cat'), array('dog'), array('cat'), array('cat'), array('cat'), array('cat'), array('cat'), array('cat'), array('dog'), array('cat'), array('cat'), array('cat'), array('cat'), array('cat'), array('cat'), array('dog'), array('cat'), array('cat'), array('cat'), array('cat'), array('cat'), array('cat'), array('dog'), array('cat'), array('cat'), array('cat') );
this needs dynamic since don't know size of array 1 or 2 (they change in time). needs account odd or , distributed possible. true constant array 2 shorter array 1.
the repeating arrays cat , dog illustrative purposes. actual values of these arrays can assume each it's own.
you can use following function. assumed elements in both arrays may have different values , array keys may not ordered.
function distribute($container, $distributed) { // reindex arrays $container = array_values($container); $distributed = array_values($distributed); $containersize = count($container); $distributedsize = count($distributed); $partsize = floor($containersize / $distributedsize); $newarray = array(); $distributedkey = 0; $newarraykey = 0; foreach ($container $containerkey => $containervalue) { if (($containerkey >= $partsize) && (($containerkey % $partsize) == 0)) { $newarray[$newarraykey] = $distributed[$distributedkey][0]; $distributedkey++; $newarraykey++; } $newarray[$newarraykey] = $container[$containerkey][0]; $newarraykey++; } return $newarray; }
Comments
Post a Comment