0

Trying to alphabetically merge arrays with foreach loop.

<?php
$fruits = array(
    'Apple' => array('ids'=>array(1,2)),
    'Banana' => array('ids'=>array(3,4)),
    'Ananas' => array('ids'=>array(5,6))
    );

$result = array();

foreach ($fruits as $name=>$subarr) {
    $first_letter = mb_substr($name, 0, 1);

    $result[$first_letter] = $subarr;
}

print_r($result); gives me smth like

Array
(
    [A] => Array
        (
            [ids] => Array
                (
                    [0] => 5
                    [1] => 6
                )
        )

[B] => Array
    (
        [ids] => Array
            (
                [0] => 3
                [1] => 4
            )
    )

)

instead of smth like

    [A] => Array
        (
            [ids] => Array
                (
                    [0] => 1
                    [1] => 2
                    [2] => 5
                    [3] => 6
                )
        )

how can I fix it?

1
  • Can you explain why you expected this array structure? Commented Jan 9, 2016 at 5:06

2 Answers 2

1

You overwrite your result every iteration in this line:

$result[$first_letter] = $subarr;

Just create a new array if the subArray in the result array doesn't exists and merge the ids subArray into your result array.

foreach ($fruits as $name=>$subarr) {
    $first_letter = mb_substr($name, 0, 1);

    if(!isset($result[$first_letter]))
        $result[$first_letter] = [];
    $result[$first_letter] = array_merge($result[$first_letter], $subarr["ids"]);
}
Sign up to request clarification or add additional context in comments.

Comments

0

Please try to use foreach loop.

$fruits = array(
    'Apple' => array('ids'=>array(1,2)),
    'Banana' => array('ids'=>array(3,4)),
    'Ananas' => array('ids'=>array(5,6))
    );

$result = array();
foreach ($fruits as $name=>$subarr) {
    $first_letter = mb_substr($name, 0, 1);
    foreach($subarr as $key=>$value){
        foreach ($value as $gkey => $gvalue) {
            $result[$first_letter]['ids'][] = $gvalue;
        }

    }
}

echo "<pre>";
print_r($result);

Display above code output like below.

Array
(
    [A] => Array
        (
            [ids] => Array
                (
                    [0] => 1
                    [1] => 2
                    [2] => 5
                    [3] => 6
                )

        )

    [B] => Array
        (
            [ids] => Array
                (
                    [0] => 3
                    [1] => 4
                )

        )

)

Comments

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.