Search code examples
phparrayslaravelarray-merge

Array Merge PHP keeps creating Child/Dimensional Array


I have been trying to solve this issue for the few days. I have gotten nowhere with it. My website has an option to choose what subjects you are doing in school: The front-end part works great and I am able to get save the result in my table in the column subjects.

The issue comes when adding multiple subjects: it creates a child for every subject I add. This, when a few subjects have been added results in something like this:

[
{
    "subject": {
        "level": "hl",
        "subject": "mathematics"
    }
},
[
    {
        "subject": {
            "level": "hl",
            "subject": "french"
        }
    },
    [
        {
            "subject": {
                "level": "hl",
                "subject": "history"
            }
        }
    ]
]
]

As you can see, every time a user adds a subject a child is created to hold that any previous subjects that were added. What I am trying to achieve is something like this:

[
{
    "subject": {
        "level": "hl",
        "subject": "mathematics"
    }
},
{
    "subject": {
        "level": "hl",
        "subject": "french"
    }
},  
{
    "subject": {
        "level": "hl",
        "subject": "history"
    }
}
]

The PHP code that I use for merging the two arrays together is as follows:

    //The user selected subject 
    $input = $request->only(['subject', 'level']);

    //Make a user model
    $user = Auth::user();

    //Format for array
    $add_subject['subject'] = [
        'subject' => $input['subject'],
        'level' => $input['level'],
    ];

    //Get the subjects the user already has from the user model
    $user_subjects = $user->subjects;

    //Make the two arrays
    $array1 = array($add_subject);
    $array2 = array($user_subjects);

    //Merge the two arrays
    $merge = array_merge($array1, $array2);

    //Save the array in database
    $user->subjects = $merge;
    $user->save();

Basically my code is currently creating an array for each subject. Is there any way to prevent it from happening?


Solution

  • The problem with your code lies in here:

    $array2 = array($user_subjects);
    

    As i am guessing that $user_subjects is already an array, so you are making it an array with an array inside. Also, you don't really need to use array_merge. This should work as well:

    $user_subjects[] = $add_subject;