0

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
)   
12
  • Can show us how exactly the result should be? Commented Oct 21, 2016 at 13:38
  • yeah sure.Let me update my Question again. Commented Oct 21, 2016 at 13:38
  • so you want 'string1' as key and next numbers as values? Commented Oct 21, 2016 at 13:40
  • It would be a better idea to look at how you created this array in the first place and create it there as you actually want it to be Commented Oct 21, 2016 at 13:43
  • 1
    I think that re-arranging everything in one big multi-dimensional array is a better idea than generating loads of new variables that after this re-ordering might or might not exist. Commented Oct 21, 2016 at 13:52

1 Answer 1

2

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

Sign up to request clarification or add additional context in comments.

1 Comment

Works awesome.Thank you for help.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.