1

i have a string this one: position1, position2

Basically i want to have this kind of structure -

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.

5
  • 1
    ['position'=>'position1', 'position'=>'position2'] <-- this doesn't make any sense Commented Aug 3, 2018 at 12:53
  • i want to convert it into javascript object later. Thats why i need this kind of structure) . Commented Aug 3, 2018 at 12:54
  • i want to convert it into javascript object later... maybe we are talking about a XY-problem... as said before it does NOT make any sense having an array with same keys and different values...not sure even if this is valid Commented Aug 3, 2018 at 12:55
  • PHP array cannot contain the same key twice. What would You expect $array['position'] to return? Commented Aug 3, 2018 at 12:56
  • i want to make structure like js object (array of objects). for example: [{position:position1},{'position:position2}] is it posible using php and convert it into Js Commented Aug 3, 2018 at 12:58

2 Answers 2

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'))
Sign up to request clarification or add additional context in comments.

1 Comment

Thank you! this is what i was looking for.
1

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

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

2 Comments

foreach($positions as $pose) { $modPoses[]['position'] = $pose; }
@splash58 multiple ways

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.