2

The question is simple, I want to create the array below dynamically, but the code I got now only outputs the last row. Is there anybody who knows what is wrong with my dynamically array creation?

$workingArray = [];
$workingArray =
[
    0 =>
    [
        'id' => 1,
        'name' => 'Name1',
    ],
    1 =>
    [
        'id' => 2,
        'name' => 'Name2',
    ]
 ];
echo json_encode($workingArray);


/* My not working array */
$i = 0;
$code = $_POST['code'];
$dynamicArray = [];
foreach ($Optionsclass->get_options() as $key => $value) 
{
    if ($value['id'] == $code) 
    {
        $dynamicArray =
        [
            $i =>
            [
                'id' => $key,
                'name' => $value['options']
            ]
        ];
        $i++;
    }
} 
echo json_encode($dynamicArray);

2 Answers 2

2

You dont need to have the $i stuff that is adding another level to your array that you dont want.

$code = $_POST['code'];
$dynamicArray = [];
foreach ($Optionsclass->get_options() as $key => $value) 
{
    if ($value['id'] == $code) 
    {
        $dynamicArray[] = ['id' => $key, 'name' => $value['options'];
    }
} 
echo json_encode($dynamicArray);
Sign up to request clarification or add additional context in comments.

1 Comment

Awesome, this is working nicely! Great for the very quick answer too.
2

You are creating a new dynamic array at each iteration:

$dynamicArray =
        [
            $i =>
            [
                'id' => $key,
                'name' => $value['options']
            ]
        ];

Instead, declare $dynamicArray = []; above the foreach, and then use:

array_push($dynamicArray, [ 'id' => $key, 'name' => $value['options']);

inside the array.

1 Comment

Also thanks for the working answer and for the very quick reply!

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.