Rorschach Rorschach - 1 month ago 7
PHP Question

Build array by string name OR make multiple array by string values

I want to build a array or multiple array by breaking the main array , and my array is like ,

Array
(
[0] => string1
[1] => 1
[2] => 2
[3] => 3
[4] => 66
[5] => 34
[6] => string1
[7] => aww
[8] => brr
[9] => string3
[10] => xas

)


So basically by the value 'string1' i want to make a new array or first array which has only those three values (1,2,3) and same for string2 and string3,So each array has its values(three).
Please help me to build this.
Note: those all string names will be static.

Thank you in advance.

Result should me like:

string1 array:
<pre>Array
(
[1] => 1
[2] => 2
[3] => 3
[4] => 66
[5] => 34
)

string2 array:
<pre>Array
(
[1] => aww
[2] => brr
)

string3 array:
<pre>Array
(
[1] => xas
)

Answer

This I think will get you what you want.

It does assume that the first entry in the old array will be a keyword!

$old = array('string1',1,2,3,66,34,'string2','aww','brr','string3','xas');
$new = array();

$keywords = array('string1', 'string2', 'string3');
$last_keyword = '';

foreach ($old as $o) {
    if ( in_array($o, $keywords) ) {
        $last_keyword = $o;        
    } else {
        $new[$last_keyword][] = $o;
    }
}

print_r($new);

It creates a new array like this

Array
(
    [string1] => Array
        (
            [0] => 1
            [1] => 2
            [2] => 3
            [3] => 66
            [4] => 34
        )

    [string2] => Array
        (
            [0] => aww
            [1] => brr
        )

    [string3] => Array
        (
            [0] => xas
        )

)

However I still maintain that it would be better to go back to where the original array gets created and look to amend that process rather than write a fixup for it

Comments