-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
  • 741,623
  • 53
  • 500
  • 612
  • thanks it work, but i forgot and i have a problem i need it like this: ````{ "results": [ { "id": 1, "text": "Option 1" }, { "id": 2, "text": "Option 2" } ], "pagination": { "more": true } }```` how can i add the Result to it? – BRABO Jul 02 '21 at 16:55
  • I don't see how that're related to the input you show. Please edit the question to clarify. – Barmar Jul 02 '21 at 16:58
  • Show what the result should be with values like `johnjohn` – Barmar Jul 02 '21 at 16:59
  • Its edited, sorry for the bad expose of the problem – BRABO Jul 02 '21 at 16:59