-3

My array:

Array
(
    [0] => ABC A
    [1] => ABC B
    [2] => Array
        (
            [0] => DEF
            [1] => ABC A
        )

    [3] => Array
        (
            [0] => DEF
            [1] => ABC B
        )

    [4] => Array
        (
            [0] => GHI
            [1] => ABC A
        )

    [5] => Array
        (
            [0] => GHI
            [1] => ABC B
        )

)

My goal is to create an array like this:

Array
(
    [0] => ABC A
    [1] => ABC B
    [2] => Array
        (
            [0] => DEF
            [1] => ABC A
            [2] => ABC B
        )

    [3] => Array
        (
            [0] => GHI
            [1] => ABC A
            [2] => ABC B
        )

)

I don't know how to solve this problem.

4
  • 1
    @Ganesh: Not sure how that will help here. Commented May 9, 2014 at 7:55
  • This may help you stackoverflow.com/questions/14202108/… Commented May 9, 2014 at 7:55
  • 1
    i can't understand the way you want it te be orderer and merged Commented May 9, 2014 at 7:56
  • 2
    "My goal is to create an array like this" - huh? you have to explain the rule. voted to close. Commented May 9, 2014 at 7:59

1 Answer 1

3

You can just use plain ol' foreach on this one. Consider this example:

$values = array(
    'ABC A',
    'ABC B',
    array('DEF', 'ABC A'),
    array('DEF', 'ABC B'),
    array('GHI', 'ABC A'),
    array('GHI', 'ABC B'),
);

$new_values = array();
foreach($values as $key => $value) {
    if(is_array($value)) {
        $new_values[$value[0]][0] = $value[0];
        $new_values[$value[0]][] = $value[1];
    } else {
        $new_values[] = $value;
    }
}

$new_values = array_values($new_values); // reindex

print_r($new_values);

Sample Output:

Array
(
    [0] => ABC A
    [1] => ABC B
    [2] => Array
    (
        [0] => DEF
        [1] => ABC A
        [2] => ABC B
    )

    [3] => Array
    (
        [0] => GHI
        [1] => ABC A
        [2] => ABC B
    )

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

2 Comments

ohh my god, do not forget to always give this people the happiness. really thankyou it's work
+1 for managing to understand the question!

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.