如何使用php将普通数组转换为关联数组

时间:2022-09-26 08:21:42

i have a string this one: position1, position2

我有一个字符串这个:position1,position2

Basically i want to have this kind of structure -

基本上我想拥有这种结构 -

array( array('position' => 'position 1'), array('position' => 'position 2') )

array(array('position'=>'position 1'),array('position'=>'position 2'))

i have tried this so far.

到目前为止我已经尝试过了。

$positions = explode(',', "position1, position2");

    $modPoses = [];

    foreach($positions as $pose):
        $modPoses['position'] = $pose;
    endforeach;

    print_r($modPoses);

Output:

Array ( [position] => position2 )

How can i get desired(mentioned above) array structure? Thank you.

我怎样才能得到(上面提到的)数组结构?谢谢。

2 个解决方案

#1


1  

I guess that what You want is:

我猜你想要的是:

array(
    array('position' => 'position 1'),
    array('position' => 'position 2')
)

If that is so, You can use:

如果是这样,您可以使用:

array_map(function ($i) { return array('position' => $i); }, explode(',', 'position 1, position 2'))

#2


2  

It does not make any sense that you assign two values to same index but let me give you a solution. If you use 2d associative array then you can do it in this way

将两个值分配给相同的索引没有任何意义,但让我给你一个解决方案。如果你使用2d关联数组,那么你可以这样做

$counter = 0; //initialize counter here
foreach($positions as $pose):
        $modPoses[$counter]['position'] = $pose;
        $counter++;
     endforeach;

#1


1  

I guess that what You want is:

我猜你想要的是:

array(
    array('position' => 'position 1'),
    array('position' => 'position 2')
)

If that is so, You can use:

如果是这样,您可以使用:

array_map(function ($i) { return array('position' => $i); }, explode(',', 'position 1, position 2'))

#2


2  

It does not make any sense that you assign two values to same index but let me give you a solution. If you use 2d associative array then you can do it in this way

将两个值分配给相同的索引没有任何意义,但让我给你一个解决方案。如果你使用2d关联数组,那么你可以这样做

$counter = 0; //initialize counter here
foreach($positions as $pose):
        $modPoses[$counter]['position'] = $pose;
        $counter++;
     endforeach;