user5534204
user5534204

Reputation:

How can I get a value from a json string?

I have a JSON string in this variable:

$value = $request->pre_departure_type;

With the value:

"30":0 ,"31":2

I want to get the values 30 and 0, 31 and 2 from the above JSON string.

I tried this code:

$result = array();

foreach (explode(',', $value) as $sub) {
    $subAry = explode(':', $sub);
    $result[$subAry[0]] = $subAry[1];
}

But this didn't explode the string on the double quotes.

Upvotes: -1

Views: 88

Answers (5)

Parth Chavda
Parth Chavda

Reputation: 1829

$value = '{"30":0 ,"31":2}'; // this is a json

$data = json_decode($value); // json to object

foreach($data as $key=>$value)
{
echo $key;  // get key
echo $value; //get value
}

get values 30 and 0 , 31 and 2 from above

Upvotes: 0

Santosh Patel
Santosh Patel

Reputation: 539

If You are getting the perfect answer from your code then i think there is a problem because of double inverted comma. firstly remove it.

$str = str_replace('"', '', $value);

You will get value like below

value = 30:0 ,31:2

after that you will convert it in to array.

Upvotes: 1

PRANAV
PRANAV

Reputation: 629

your value coming as a json format so first you need to convert it to object and then array and do manipulation as follow

$valueArr=(array)json_decode($value);
$finalArray=array();
foreach($valueArr as $k=>$v){
    array_push($finalArray,$k);
    array_push($finalArray,$v);
}
echo "<pre>";print_r($finalArray);

Upvotes: 0

Waqas Shahid
Waqas Shahid

Reputation: 1060

If you are getting your desired result but with quotations then simply use this function to remove quotations:

$str = str_replace('"', '', $string_to_replace);

Upvotes: 0

akhilp2255
akhilp2255

Reputation: 330

First replace double quotes and then do the same process as you did.

$result = array();
$newvalue = str_replace('"', '', $value);
foreach (explode(',', $value) as $sub) {
    $subAry = explode(':', $sub);
    $result[$subAry[0]] = $subAry[1];
}

Upvotes: 0

Related Questions