0

I want to add a foreach inside an array or build two arrays to send API requests.

The correct format that I'm trying to achieve is:

'products'           => [
        [
            'name'          => 'x',
            'code'          => '',
            'description'   => '',
            'price'         => '1',
            'measuringUnit' => '',
            'currency'      => 'EUR',
        ],
        [
            'name'          => 'y',
            'code'          => '',
            'description'   => '',
            'price'         => '2',
            'measuringUnit' => '',
            'currency'      => 'EUR',
        ]
    ],

I know that I cannot run code inside array() so I'm trying to build two arrays and merge them. The problem is that if I'm not getting the correct syntax the API server is rejecting my request.

[products] => Array ( [0] => Array[ [name] => x, [code] => '', [description] => '', [price] => 1.00, [measuringUnit] => '', [currency] => EUR, ], [ [name] => y, [code] => '', [description] => '', [price] => 2, [measuringUnit] => '', [currency] => EUR, ], )

Spent hours but I cannot get a solution.

What I did so far: I have added the $defaultData with:

$defaultData = array(
    'products'           => [],
);

And trying to build the foreach for multiple items:

$add_array=[];
    foreach($results['items']['item'] as $key) {
        $description=$key['description'];
        $amount=$key['amount'];
        $add_array.="[
                    'name'          => $description,
                    'code'          => '',
                    'description'   => '',
                    'price'         => $amount,
                    'measuringUnit' => 'buc',
                    'currency'      => $currency_code,
            ],
        ";
    }
    $defaultData['products'][0].=$add_array;

tried also with array_merge() and array_push(), but I cannot get the exact format as is requested for the API. The problem is that the foreach is creating multidimensional vector for using array_push().

Thanks!

0

1 Answer 1

0

Just add each subarray [] in the loop:

foreach($results['items']['item'] as $key) {
    $defaultData['products'][] = [
                'name'          => $key['description'],
                'code'          => '',
                'description'   => '',
                'price'         => $key['amount'],
                'measuringUnit' => 'buc',
                'currency'      => $currency_code
    ];
}
Sign up to request clarification or add additional context in comments.

1 Comment

Sorry, just accepted the answer. Thank you once again!

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.