我正在努力构建一个对象的对象,而不是一个对象数组(这有效,但稍后与 json 一起使用不太容易)
使用http://writecodeonline.com/php/进行测试
$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"}]
我希望能够轻松地执行 $arr['name'] 或 $arr['friend']
编辑:像那样工作(谢谢 Dani):我对 Php 完全不熟悉,所以如果有人可以解释(JSON_FORCE_OBJECT 选项没有解决它)
$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"}