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

3
  • You started good but then ended not showing what you actually tried. Have you tried anything? Commented Jul 3, 2017 at 13:04
  • You can use json_decode() and json_encode() to encode/decode json string/ php array Commented Jul 3, 2017 at 13:05
  • look at below link Hope it will help you. stackoverflow.com/questions/1116708/getting-first-json-property Commented Jul 3, 2017 at 13:41

2 Answers 2

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

1 Comment

I do not want all data just need id values in json format
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));

7 Comments

App\Http\Controllers\stdClass' not found error i found
If you are using Laravel try $ids = new \stdClass();
s {"id1":1,"id2":3,"id3":4}
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
{#605 ▼ +"id1": 1 +"id2": 3 +"id3": 4 }
|

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.