Question:
How you can create array with associative array in other array php?

In PHP, you can create an array that contains associative arrays by defining each associative array as an element within the outer array. Each associative array represents a key-value pair structure. 


So you need to adjust your loop:

$metaDataList = [];


foreach ($precontractData->items as $i => $item) {

    $metaDataList[] = [

        'key' => "item_description{$i}",

        'value' => $item->name,

    ];

    $metaDataList[] = [

        'key' => "item_quantity{$i}",

        'value' => intval($item->cuantity),

    ];

}


Final $metaDataList will be similar to

You are constructing your array wrongly. There is no keys named item_description_0, just key and value. So you need to adjust your loop:


$metaDataList = [];


foreach ($precontractData->items as $i => $item) {

    $metaDataList[] = [

        'key' => "item_description{$i}",

        'value' => $item->name,

    ];

    $metaDataList[] = [

        'key' => "item_quantity{$i}",

        'value' => intval($item->cuantity),

    ];

}

Final $metaDataList will be similar to


[

    [

        'key' => 'item_description0',

        'value' => 'Name',

    ],

    [

        'key' => 'item_quantity0',

        'value' => 100,

    ],

    [

        'key' => 'item_description1',

        'value' => 'Name 1',

    ],

    [

        'key' => 'item_quantity1',

        'value' => 101,

    ],

];


Credit:> StackOverflow


Suggested Blogs: 

>How to solve XGBoost model training fails in Python

>Python Error Solved: load_associated_files do not load a txt file

>How to build interactive_graphviz in Python

>How to solve encoding issue when writing to a text file, with Python?

>Python Error Solved: pg_config executable not found



Ritu Singh

Ritu Singh

Submit
0 Answers