-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.

0

1 Answer 1

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

4 Comments

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?
I don't see how that're related to the input you show. Please edit the question to clarify.
Show what the result should be with values like johnjohn
Its edited, sorry for the bad expose of the problem

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.