rwur
rwur

Reputation: 247

Loop through PHP array with foreach and array_keys

I have an array $texts which looks like this:

Array
(
    [CAR_SINGULAR] => Array
        (
            [id] => 1
            [translations] => Array
                (
                    [de] => Auto
                    [en] => Car
                )
        )
    [CAR_PLURAL] => Array
        (
            [id] => 2
            [translations] => Array
                (
                    [de] => Autos
                    [en] => cars
                )
        )
)

and then I have this piece of PHP code where I want to output the array with a simple h1 and an input type text for each of the translation country codes.

foreach(array_keys($texts) as $text)
{ 
    echo "<h1>". $text ."</h1>";

    foreach($texts[$text] as $textData) 
    {  
        foreach(array_keys($textData) as $languageCode)
        {
            echo $languageCode .": <input type=\"text\" id=\"". $ID_OF_CODE_AND_TEXTID ."\" value=\"". $VALUE_OF_LANGUAGE_CODE ."\" /><br />";   
        }       
    } 
}

The result should be-

<h1>CAR_SINGULAR</h1>
de: <input type="text" id="de_1" value="Auto" /><br />
en: <input type="text" id="en_1" value="car" />

<h1>CAR_PLURAL</h1>
de: <input type="text" id="de_2" value="Autos" /><br />
en: <input type="text" id="en_2" value="cars" />

but somehow I am too blind to add the id and the value to the input :-(

Any help would be appreciated :-)

Upvotes: 1

Views: 217

Answers (1)

Andreas
Andreas

Reputation: 23958

You have to add the html but this is the basic output:

$texts  = Array
(
    "CAR_SINGULAR" => Array
        (
            "id" => 1,
            "translations" => Array
                (
                    "de" => "Auto",
                    "en" => "Car"
                )
        ),
    "CAR_PLURAL" => Array
        (
            "id" => 2,
            "translations" => Array
                (
                    "de" => "Autos",
                    "en" => "cars"
                )
        )
);

foreach($texts as $key => $subarr){
    echo $key. "\n";
    foreach($subarr["translations"] as $lang => $val){
        echo $lang . ": " . $val . "\n";
    }
    echo "\n";
}

The Key of the first array is plural/singular.
Then I loop the inner subarray and output it's values in "translations".

https://3v4l.org/4AGmW

Upvotes: 1

Related Questions