Home > Blockchain >  Array merge or combine by same key of two associative arrays?
Array merge or combine by same key of two associative arrays?

Time:01-31

I have this situation:

$array = [
    "name" => [
        "ro" => [
            0 => "Nume Romana",
        ],

        "en" => [
            0 => "Nume Engleza",
        ],

        "fr" => [
            0 => "Nume Franceza",
        ],
    ],

    "meta_keywords" => [
        "ro" => [
            0 => "keywords romana",
        ],

        "en" => [
            0 => "keywords Engleza",
        ],
        "fr" => [
            0 => "keywords Franceza",

        ],
    ],

    "meta_description" => [
        "ro" => [
            0 => "desciption romana",
        ],
        "en" => [
            0 => "desciption Engleza",
        ],
        "fr" => [
            0 => "desc Franceza",
        ],
    ],
];

And I want to group samething like this:

$result = [
    "ro" => [
        "name" => "Nume Romana",
        "meta_keywords" => "keywords romana",
        "meta_description" => "desciption romana",
    ],

    "en" => [
        "name" => "Nume Romana",
        "meta_keywords" => "keywords romana",
        "meta_description" => "desciption romana",
    ],
];

I tried with array_merge_recursive(), foreach , array_combine(), but without result. can someone help me?

CodePudding user response:

You can use a nested foreach loop to iterate over the arrays and reformat the data:

$result = [];
foreach ($array as $key => $value) {
    foreach ($value as $language => $translation) {
        $result[$language][$key] = $translation[0];
    }
}

This will produce the desired output:

$result = [
    "ro" => [
        "name" => "Nume Romana",
        "meta_keywords" => "keywords romana",
        "meta_description" => "desciption romana",
    ],

    "en" => [
        "name" => "Nume Engleza",
        "meta_keywords" => "keywords Engleza",
        "meta_description" => "desciption Engleza",
    ],

    "fr" => [
        "name" => "Nume Franceza",
        "meta_keywords" => "keywords Franceza",
        "meta_description" => "desc Franceza",
    ],
];
  • Related