$res = array:3 [▼
0 => array:18 [▼
"id" => 1
"smval" => "xys"
]
1 => array:18 [▼
"id" => 3
"smval" => "asss"
]
2 => array:18 [▼
"id" => 4
"smval" => "deg"
]
]
期待结果:
{first_id:1,second_i d:3,third_id:4}
我想将此数组转换为object。所以我可以打电话给ajax
{first_id:1,second_i d:3,third_id:4}
答案 0 :(得分:0)
使用json_encode
将Array转换为Json。
$res = [ 0 => [ "id" => 1, "smval" => "xys" ],
1 => [ "id" => 3, "smval" => "asss" ],
2 => [ "id" => 4 , "smval" => "deg" ]
];
$json = json_encode($res);
print_r($json);
答案 1 :(得分:0)
您可以使用动态属性来实现:
$ids = new \stdClass(); //Laravel way due to namespacing
//$ids = new stdClass(); //create a generic empty object
$count = 1;
foreach ($res as $key=>$val){
$ids->{"id".($count++)} = $val["id"]; //assign the property to the object dynamically
}
echo(json_encode($ids));
或者,如果您需要一组特定的名称,可以使用另一个数组作为名称:
$ids = new \stdClass(); //Laravel way due to namespacing
//$ids = new stdClass(); //create a generic empty object
$names = ["name1", "name2", "name3"];
$count = 0;
foreach ($res as $key=>$val){
$ids->{$names[$count++]} = $val["id"]; //assign the property to the object dynamically based on the names array
}
echo(json_encode($ids));