【问题标题】:Get data from inside array in Php从 PHP 中的数组内部获取数据
【发布时间】:2019-08-19 04:21:21
【问题描述】:

使用查询我得到数组中的结果,我想在一个数组中获取这些数据, 我得到如下方式的结果

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);
}

【问题讨论】:

  • 查看您想要访问的数组的示例会很有用
  • 你可以使用result_array()而不是result()然后你会得到一个纯数组的查询结果
  • 只有数据?因为数组中不能有重复的键。
  • 但对我不起作用你的意思是它正在崩溃吗?你的意思是它没有生成你想要的数组吗?请记住,我们不是在看着您,只有在您向我们提供足够的信息以提供帮助时,我们才能提供帮助
  • @MasivuyeCokile:如果我使用 result_array,那么数据来自数组内的数组

标签: php mysql arrays codeigniter


【解决方案1】:

您可以轻松循环并获取数组中的值,如下所示。

$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);

【讨论】:

  • @Arafind Bhat K:我想要关联数组而不是数字/索引
  • 更新了我的答案,请检查。它现在应该为你工作。 @NidhiGupta
【解决方案2】:

只需使用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
        )

)

【讨论】:

    猜你喜欢
    • 2021-11-04
    • 2018-07-30
    • 2013-04-04
    • 1970-01-01
    • 2019-07-04
    • 1970-01-01
    • 1970-01-01
    • 2019-05-01
    相关资源
    最近更新 更多