PHP Loop through an associative array

Viewed 1097

Edited to provide clarifications, based on the comments.

I have a dynamic associative array with keys and values that looks like this:

array: ["apples" => 4   "bananas" => 4   "cherries" => 4   "dates" => 3]

I would like to create another n-sized array (with dynamic n) that will loop through the array in series.

Example:

(if n = 6):

apples, cherries, apples
bananas, dates, bananas
cherries, apples, cherries
dates, bananas
apples, cherries
bananas, dates

n range is between 1 and sum of all values

the code I have so far is this:

function makeArray($commonWords){
  $n = 6;
  $result = array_fill(0,$n, '');
  $i = 0;

  while (list($key, $value) = each($commonWords)) {
    $result[$i] = $result[$i] . $key;
    $i++;
  }

  return $result;
}

Which provides this output:

array:6 [▼
  0 => "apples"
  1 => "bananas"
  2 => "cherries"
  3 => "dates"
  4 => ""
  5 => ""
]

But the 5th line needs to be "apples", the sixth needs to be "bananas". Then on first line after "apples" needs to have "cherries", and so on, as in the example above.

Hope this provides clarification.

2 Answers
Related