-2

I want to make multiple array by php (Laravel 5). There are two arrays as follows.

$tags=['en' =>[]];
$TAGS = ['test1','test2','test3',...]

I want to make this array as a return value in certain code like this:

return [
    'tags' => [
        'en' => [
            'test1' => 'test1',
            'test2' => 'test2',
            'test3' => 'test3',
            ...
        ]
    ]
]

I tried the following, but it did not work.

return [
    'tags' => [
        'en' => [
            foreach($TAGS as $TT)
                array_push($tags['en'], $TT);
        ]
    ]
]

Is there any other way?

3
  • you can use the foreach and create a new array $en and then in the original array you can do 'en' => $en Commented Oct 23, 2017 at 5:56
  • Possible duplicate of PHP dynamic array index name Commented Oct 23, 2017 at 5:57
  • Have you tried my answer? Commented Oct 23, 2017 at 6:05

2 Answers 2

0

Try like this :

<?php
$mainArray = array("EN","IT","SP"....);
$returnArray = array();
foreach($mainArray as $key => $value){
    //Create the sub array here as you want it.
    $subArray = [
        "Test1" => "test1",
        "Test2" => "test2",
        "Test3" => "test3"
    ];        
    array_push($returnArray[$value],$subArray);
}

return $returnArray;
?>
Sign up to request clarification or add additional context in comments.

1 Comment

reply thanks, I'msorry, "Only variables can be passed by reference error" occured.
0

Try this -

$json = array();
$langs = ['en','fr'];
$tags = ['test1','test2','test3'];
 foreach ($langs as $lang) {
    $json[$lang] = [];
    foreach ($tags as $tag) {
        $json[$lang][] = $tag;
    }
 }
return $json;

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.