Piet
Piet

Reputation: 2208

PHP - How to create such array?

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);

Upvotes: 2

Views: 36

Answers (2)

jconder
jconder

Reputation: 746

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.

Upvotes: 2

RiggsFolly
RiggsFolly

Reputation: 94642

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);

Upvotes: 2

Related Questions