0

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.

Rizier123
  • 58,877
  • 16
  • 101
  • 156

5 Answers5

1

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.

Santosh Patel
  • 549
  • 2
  • 13
0

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];
}
akhilp2255
  • 330
  • 3
  • 13
0

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

$str = str_replace('"', '', $string_to_replace);
Waqas Shahid
  • 1,051
  • 1
  • 7
  • 22
0

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);
PRANAV
  • 629
  • 4
  • 13
0
$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

Parth Chavda
  • 1,819
  • 1
  • 23
  • 30