I’m struggling to build an object of objects, instead of an array of objects, (that works but is less easy to use later with json)
use http://writecodeonline.com/php/ for testing it
$a = Array();
$obj = new stdClass();
$obj->key = "name";
$obj->value = "durant";
array_push($a, $obj);
$obj = new stdClass();
$obj->key = "friend";
$obj->value = "johns";
array_push($a, $obj);
$preds = Array();
foreach( $a as $v ){
$item = Array(); // new stdClass();
$item[$v->key] = $v->value; // ^ doesn't work
array_push($preds, $item);
}
$obj = new stdClass();
$obj->key = "data";
$obj->value = $preds;
array_push($a, $obj);
//var_dump($a);
echo(json_encode($a[2]->value)); // returns: [{"name":"durant"},{"friend":"johns"}]
I would like to be able to easily perform $arr[‘name’] or $arr[‘friend’]
EDIT: works like that (thx Dani): I’m totally noob to Php, so If someone can explain (the JSON_FORCE_OBJECT opts did not solved it)
$a = Array();
$obj = new stdClass();
$obj->key = "name";
$obj->value = "durant";
array_push($a, $obj);
$obj = new stdClass();
$obj->key = "friend";
$obj->value = "johns";
array_push($a, $obj);
$preds = new stdClass();
foreach( $a as $v ){
$k = $v->key;
$preds->$k = $v->value;
}
$obj = new stdClass();
$obj->key = "data";
$obj->value = $preds;
array_push($a, $obj);
echo(json_encode($a[2]->value)); // returns: {"name":"durant", "friend":"johns"}
You can use variable variables: