Scott Scott - 3 months ago 15
PHP Question

How can I build a dynamic array from a string in PHP?

I'm trying to create an array in PHP that has the structure defined by a string. It will loop through and use the first value as the value and the second value as the quantity. For instance the 1|3 will have the value of 1, 3 times and then loop to the next in the string.

Here is what I have so far -

<?php

$quantity = 10;
$string = '1|3,2|3';
$overall_types = array( );

$types = explode( ',', $string );

for ( $i = 1; $i <= $quantity; $i++ )
{
$qc = explode( '|', $types[0] );
$overall_types[$i] = $qc[0];
}

echo '<pre>';
print_r ( $overall_types );
echo '</pre>';


and that gets me

Array
(
[1] => 1
[2] => 1
[3] => 1
[4] => 1
[5] => 1
[6] => 1
[7] => 1
[8] => 1
[9] => 1
[10] => 1
)


but, I want the result to be

Array
(
[1] => 1
[2] => 1
[3] => 1
[4] => 2
[5] => 2
[6] => 2
[7] => 1
[8] => 1
[9] => 1
[10] => 2
)


I'm not sure how to easily switch between the exploded values.

Thanks.

Answer

You're not using the repetition count at all from what I see. Achieving this using a straight-forward approach is tricky and probably not necessary when there's a simpler way to do this.

<?php
function buildReps($string) {
    $array = [];
    $overall_types = array( );
    $types = explode( ',', $string );
    foreach ($types as $type) {
         $qc = explode( '|', $type );
         $array = array_merge($array, array_fill(0, $qc[1], $qc[0]));
    }
    return $array;
}

function buildAllReps($string, $quantity) {
     $array = [];

     while (count($array) < $quantity) {
          $array = array_merge($array, buildReps($string));
     } 
     return array_slice($array, 0, $quantity); 
}

$quantity = 10;
$string = '1|3,2|3';

echo '<pre>';
print_r ( buildAllReps($string, $quantity) );
echo '</pre>';    

The first function builds the array once based on the $string defintion. The second one just merges the results from the first one until you reach quantity and then stops and returns the correct quantity of items back.

The above outputs:

Array
(
    [0] => 1
    [1] => 1
    [2] => 1
    [3] => 2
    [4] => 2
    [5] => 2
    [6] => 1
    [7] => 1
    [8] => 1
    [9] => 2
)

Example in https://eval.in/629556

Beware of infinite loops which may occur if the definition supplied by $string does not produce a non-empty array.