-2
$res = array:3 [▼
  0 => array:18 [▼
    "id" => 1
    "smval" => "xys"
  ]
  1 => array:18 [▼
    "id" => 3
    "smval" => "asss"

  ]
  2 => array:18 [▼
    "id" => 4
    "smval" => "deg"

  ]
]

Expect result :

{first_id : 1, second_i d: 3, third_id : 4}

I want to convert this array to object. So I can call in ajax

{first_id : 1, second_i d: 3, third_id : 4}

The Hungry Dictator
  • 3,444
  • 5
  • 37
  • 53
Akki Verma
  • 49
  • 7

2 Answers2

0

Use json_encode to convert Array to Json.

$res = [ 0 => [ "id" => 1, "smval" => "xys" ],
  1 => [ "id" => 3, "smval" => "asss" ],
  2 => [ "id" => 4 , "smval" => "deg" ]
];

$json = json_encode($res);

print_r($json);
Mani7TAM
  • 469
  • 3
  • 10
0

You can use dynamic properties to achieve that:

$ids = new \stdClass(); //Laravel way due to namespacing
//$ids = new stdClass(); //create a generic empty object
$count = 1;

foreach ($res as $key=>$val){
    $ids->{"id".($count++)} = $val["id"]; //assign the property to the object dynamically
}

echo(json_encode($ids));

Or if you need a specific set of names, you can use another array for the names:

$ids = new \stdClass(); //Laravel way due to namespacing
//$ids = new stdClass(); //create a generic empty object
$names = ["name1", "name2", "name3"];
$count = 0;

foreach ($res as $key=>$val){
    $ids->{$names[$count++]} = $val["id"]; //assign the property to the object dynamically based on the names array
}

echo(json_encode($ids));
Isac
  • 1,834
  • 3
  • 17
  • 24
  • App\Http\Controllers\stdClass' not found error i found – Akki Verma Jul 03 '17 at 14:14
  • If you are using Laravel try `$ids = new \stdClass();` – Isac Jul 03 '17 at 14:17
  • s {"id1":1,"id2":3,"id3":4} – Akki Verma Jul 03 '17 at 14:25
  • You can use `dd($ids);` to see if you are getting the correct array. Then i would suggesting console logging the data you are receiving in the javascript side to see if it is what you expect – Isac Jul 03 '17 at 14:27
  • {#605 ▼ +"id1": 1 +"id2": 3 +"id3": 4 } – Akki Verma Jul 03 '17 at 14:32
  • Just rendering this to view it is passing as string i guess. var res = '{{$ids}}'; console.log("s", res.'id1'); undefined – Akki Verma Jul 03 '17 at 14:33
  • It is correct then. To have a json response in laravel you need `return response(json_encode($ids))` in your controller if you dont have it already. my `echo(json_encode($ids));` was just to demonstrate how you would get the response value – Isac Jul 03 '17 at 14:33