-2

I'm working with Laravel 5 right now and I have the following problem. I've got response from DB query:

[{"id":1}]

and I want to take out 1 as int or string. Any ideas?

I've tried to solve this like follows:

$json = (DB query);       
$data = json_decode($json);     
$final = $data[0]->id;

and response is :

json_decode() expects parameter 1 to be string, array given

Krishna Mohan
  • 1,503
  • 3
  • 22
  • 28
xsalok
  • 9
  • 5

4 Answers4

2

This is all you need.

$response = json_decode($response); // Decode the JSON
$string = $response[0]->id;         // Save the value of id var
Kev Wilson
  • 470
  • 6
  • 19
1

As you say, the string you have is in JSON format, so you need to use json_decode to access it in PHP.

The square brackets refer to an array, and the braces refer to an object within that array, so what you're looking for is the id value of the first element (i.e. element 0) in the array.

<?php
$json = '[{"id":1}]';
$data = json_decode($json);

echo $data[0]->id;
// 1
iainn
  • 16,826
  • 9
  • 33
  • 40
0

Try this

$json_array = '[{"id":1}]';
$data = json_decode($json_array);
print_r($data); // To display the result array
Vinod VT
  • 6,946
  • 11
  • 51
  • 75
0

You just need to decode it, if I'm not misunderstanding your questions.

$json = '[{"id":1}]';
$decodedObject = json_decode($json);

Then you can loop through the aray and do something with your data:

foreach($decodedObject as $key => $value) {
    $id = $value->id;
}

If you're using Laravel, though, why not use Eloquent models?

Zac Brown
  • 459
  • 4
  • 12