我的问题是添加到JSON逻辑中的以下post here的变体。我使用的是PHP 5.6.22
我需要在runtim上构建一个没有对象的类来构建一个返回给客户端的相同类型的JSON对象。 我的代码:
ApplyPagingAndSorting()
运行时,我收到以下错误:
public static function getData()
{
$columns = array ("Name", "Address", "Age" );
$values = array ("John", "A Ave 222", 32 );
$ret = (object)[];
$index = 0;
foreach ($columns as $col)
{
$value = $values[$index++];
$ret[] = (object) [$col => $value]; // Error here
}
return json_encode($ret);
}
帮助解决这个问题......
答案 0 :(得分:1)
在PHP中,您可以通过设置
将新属性添加到数组$columns = array ("Name", "Address", "Age" );
$values = array ("John", "A Ave 222", 32 );
$ret = (object) [];
$index = 0;
foreach ($columns as $col)
{
$value = $values[$index++];
// You can create and add new property to object in php by such way
$ret->$col = $value;
}
echo json_encode($ret); // {"Name":"John","Address":"A Ave 222","Age":32}
答案 1 :(得分:0)
怎么样:
public static function getData()
{
$data = [
"Name" => "John",
"Address" => "A Ave 222",
"Age" => 32,
];
return json_encode($data);
}