Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

MoonFish39's avatar

How to transform input array

From the request input values = array

preview: Array ( [0] => 154 [1] => 171 [2] => 157 )

I need to transform it to:

Array ( ['id'] => 154 ['id'] => 171 ['id'] => 157 )

Tried implode etc...

0 likes
8 replies
MichalOravec's avatar
Level 75

The key in array has to be unique.

You can have an array like this

[
	'id' => 154, 
    'id' => 171, 
    'id' => 157  
]

What you can do

$data = [
  	154, 171, 157  
];

$result = collect($data)->map(function ($item) {
   return ['id' => $item]; 
})->toArray();

// the result is
[
  	['id' => 154], 
    ['id' => 171], 
    ['id' => 157]  
]
1 like
MoonFish39's avatar

Thank you,

Do you know how to get it like

            'tags'        => [
                [
                    'id' => 154,
                ],
                [
                    'id' => 171,
                ],
                [
                    'id' => 157,
                ],
    ],
MichalOravec's avatar

Exactly what I showed you above.

or you can have a name atribute like

<input type="text" name="tags[0][id]" value="154">
<input type="text" name="tags[1][id]" value="171">
<input type="text" name="tags[2][id]" value="157">
MoonFish39's avatar

Ok, is not working for woocommerce api; https://woocommerce.github.io/woocommerce-rest-api-docs/#create-a-product

Like categories, i need do it with tags only it do this in my data object.

Two times Array ( [0] => Array ( [0]

[tags] => Array ( [0] => Array ( [0] => Array ( [id] => 158 ) [1] => Array ( [id] => 154 ) [2] => Array ( [id] => 155 ) ) )

Preview my images. [images] => Array ( [0] => Array ( [id] => 6490 [alt] => saad ) ) )

Image

MoonFish39's avatar

Added a screenshot to my last reply, check this is not working for some reason...

Please or to participate in this conversation.