0

I have a $abcd variable and the following is the output:

echo $abcd;
//Output:
{ 
 "NID": 2,
 "STS": "3",
 "Options": { 
   "Model": "model value",
   "Location": "location value",
   "Price": "price value",
   "Name": "Value"
 }
}

In the "Options" I have 3 names and values of each. The names are not fixed and could be anythings and the number of objects in Options could be any from 0 to 100. I'd like to know if there is any way (JSON format preferred) that I can assign the Names and their related values to two other variables.

$varName[0]=Model
$varValue[0]=model value

$varName[1]=Location
$varValue[1]=location value

$varName[2]=Price
$varValue[2]=price value

Majid Nasirinejad
  • 107
  • 1
  • 2
  • 13

3 Answers3

1

i'm not sure what is th logic behind this,

but you may accomplish this by using mix of array_key & array_values like following:

$abcd = '{ 
 "NID": 2,
 "STS": "3",
 "Options": { 
   "Model": "model value",
   "Location": "location value",
   "Price": "price value",
   "Name": "Value"
 }
}';

$data = json_decode($abcd, true);
$keys = array_keys($data['Options']);
$values = array_values($data['Options']);


echo $keys[0] . " - " . $values[0]; // Model - model value
echo $keys[1] . " - " . $values[1]; // Location - location value
// ..... and so on.

live example: https://3v4l.org/GggRd

hassan
  • 7,812
  • 2
  • 25
  • 36
0
$data = json_decode($abcd, true);
foreach($data['Options'] as $index => $value) {
    //do whatever you want
}
//or access them directly
$data['Options']['Model']
Pavlo Zhukov
  • 3,007
  • 3
  • 26
  • 43
0

You dont need to assign them to anything else, just json_decode() the JSONString and they become a PHP Object you can use as is

$obj = json_decode($abcd);

echo $obj->Options->Model;
echo $obj->Options->Location;
echo $obj->Options->Price;

RE your comment@

I said that the names are varies and Model, Location and Price is just an example

then you could do

foreach ($obj->Options as $prop => $val) {
    sprintf( '%s = %s', $prop, $val );
}
RiggsFolly
  • 93,638
  • 21
  • 103
  • 149