通过使用查询,我正在数组中获取结果,我想在一个数组中获取此数据, 我正在按照以下方式获得结果
Array
(
[0] => stdClass Object
(
[id] => 2
[full_name] => amit sharma
)
[1] => stdClass Object
(
[id] => 1
[full_name] => amit
)
)
我尝试了以下代码,但对我不起作用,我错了,这是我的代码
$sql = "//select query";
$result= $this->db->query($sql)->result();
$total=count($result);
if($total>0)
{
$data=array();
foreach($result as $records)
{
$data[]=$records;
}
echo "<pre>";print_R($data);
}
答案 0 :(得分:0)
只需使用json_encode()和json_decode()
我已经创建了与您的示例相同的对象,只是忽略了以下代码:
$result = [$objOne, $objTwo];
使用您的$result
Json对其进行编码和解码,以得到一个关联数组。
代码:
<?php
$objOne = new stdClass();
$objOne->id = 2;
$objOne->full_name = 'amit sharma';
$objTwo = new stdClass();
$objTwo->id = 1;
$objTwo->full_name = 'amit';
$result = [$objOne, $objTwo];
$arr = json_decode(json_encode($result), TRUE);
echo '<pre>';
print_r($result);
echo '</pre>';
echo '<pre>';
print_r($arr);
echo '</pre>';
?>
输出:
Array
(
[0] => stdClass Object
(
[id] => 2
[full_name] => amit sharma
)
[1] => stdClass Object
(
[id] => 1
[full_name] => amit
)
)
Array
(
[0] => Array
(
[id] => 2
[full_name] => amit sharma
)
[1] => Array
(
[id] => 1
[full_name] => amit
)
)
答案 1 :(得分:0)
您可以轻松地循环它并获取数组中的值,如下所示。
$post_id = array((object) (array(
'id' => 1,
'full_name' => "Amit Sharma",
)), (object) (array(
'id' => 2,
'full_name' => "Amit",
)), (object) (array(
'id' => 3,
'full_name' => "Amit Rohan",
)));
foreach ($post_id as $key => $value)
{ $result[] = array("id"=>$value->id, "full_name"=>$value->full_name); }
echo "<pre>";print_r($result);