无法在php中访问数组内的对象

时间:2017-01-06 05:25:15

标签: php arrays object

我希望访问数组中的对象,下面给出了数组的样本格式,

Array
(
    [0] => stdClass Object
        (
            [id] => 1
            [user_id] => 3
            [adminid] => 1
            [payment_value] => 
        )

    [1] => stdClass Object
        (
            [id] => 2
            [user_id] => 3
            [adminid] => 2
            [payment_value] => 
        )

    [2] => stdClass Object
        (
            [id] => 3
            [user_id] => 4
            [adminid] => 3
            [payment_value] => 
        )
)

从上面的数组我希望获取所有user_id,在这个数组中它将是:

3
3
4

但是你可以看到在2个对象中user_id的值是相同的,所以在这种情况下我想进一步过滤并只取1个值,所以我想从数组得到的最终结果应该是

3
4

我不知道如何消除重复值但是我试图用来获取第一部分的代码是

print_r($rdata) // this gives the above sample array

foreach ($rdata as $key) 
    {
        $userid = $key->user_id;

        $this->db->where('id',$userid);
        $query = $this->db->get('user');
        return $query->result();
    }

通过使用上面的代码,我只得到值3作为结果,但我想要3和4

1 个答案:

答案 0 :(得分:0)

$data_collection = [
        (object)[
            "id" => 1,
            "user_id" => 3,
            "adminid" => 1,
            "payment_value" =>""
        ],
        (object)[
            "id" => 2,
            "user_id" => 3,
            "adminid" => 2,
            "payment_value" =>""
        ],
        (object)[
            "id" => 3,
            "user_id" => 4,
            "adminid" => 3,
            "payment_value" =>""
        ]
];

$user_id= [];
$i=0;
foreach ($data_collection as $single_data) {
    $user_id[$i]= $single_data->user_id;
    $i++;
}
$user_id = array_unique($user_id);
/**
 * I don't knwo what this code does to you
 */
$data_to_be_returned = [];
foreach ($user_id as $single_user_id) {
    $this->db->where('id',$single_user_id);
    $query = $this->db->get('user');
    $data_to_be_returned = [$single_user_id => $query->result()];
}

你不能在foreach循环中返回