简体   繁体   中英

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

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

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM