-1

im trying to work with Select2 with ajax as data source, and im getting the data alright but i need to convert the arrays inside my array to objs so Select2 can ''reproduce'' them as options. What i have:

  Array
    (
    [0] => Array
        (
            [0] => john
            [1] => johnjohn
        )

[1] => Array
    (
        [0] => john2
        [1] => johnjohn2
    )

[2] => Array
    (
        [0] => john3
        [1] => johnjohnjohn3
    )
.....
)

what i need:

    {
  "results": [
    {
      "id": 1,
      "text": "jhon",
      "text2": "jhonjhon"

    },
    {
      "id": 2,
      "text": "jhon2",
      "text2": "jhon22"
    }
  ]
}

As said in the documention i need to make them objects:

Select2 requires that each object contain an id and a text property. Additional parameters passed in with data objects will be included on the data objects that Select2 exposes.

I tried: How to convert an array to object in PHP? and Convert Array to Object and i cant figure it out.

BRABO
  • 100
  • 7

1 Answers1

0

Loop over the array, for each element create an associative array containing the values and push that onto the result array.

$objects = [];
foreach ($arrays as $i => $vals) {
    $objects[] = ['id' => $i+1, 'text' => $vals[0], 'text2' => $vals[1]];
}
Barmar
  • 669,327
  • 51
  • 454
  • 560