简体   繁体   English

PHP从对象中删除元素

[英]php removing an element from objects

So, I have following db result: 因此,我有以下数据库结果:

Array
(
[0] => stdClass Object
    (
        [id] => 1
        [user] => 1           
        [img] => 2016/02/img_8488.jpg
        [url] => /p=?44           
        [sent_date] => 2016-02-13 00:00:00
    )

[1] => stdClass Object
    (
        [id] => 2
        [user] => 185                     
        [img] => 
        [url] => /?p=54         
        [sent_date] => 2016-02-06 00:00:00
    )

)

How would I remove [id] and [sent_date] from the query result? 如何从查询结果中删除[id][sent_date]

I am not sure if I am using unset right. 我不确定我是否使用未设置的权利。

unset($results[0]['id']); 
$reindex = array_values($results); 
$objectarray = $reindex; 

Use unset($results[0]->id); 使用unset($results[0]->id); and unset($results[0]->sent_date) instead and it should work. unset($results[0]->sent_date) ,它应该可以工作。 If you want to do this in all of the array objects: 如果要在所有数组对象中执行此操作:

for($i = 0; $i<sizeof($results); $i++)
{
    unset($results[$i]->id);
    unset($results[$i]->sent_date);

}

Instead of removal or unset you can create a new array; 可以删除或取消设置而不是创建一个新数组。

$i = 0;
$newResult = array();
foreach($result as $value){
$newResult[$i]["user"] = $value->user;
$newResult[$i]["img"] = $value->img;
$newResult[$i]["url"] = $value->url;
$i++;
}

print_r($newResult);

$newResult will return the new array and your original array remains same you can use it if you need. $newResult将返回新数组,并且原始数组保持不变,可以根据需要使用它。

Or removal of indexes is must required than use unset inside the foreach loop as: 否则必须删除索引,然后才能在foreach循环中使用unset,如下所示:

unset($value->id); 
unset($value->sent_date);

Side note : 旁注

Also keep in mind you can not use it as $value["id"] becuase its a property not an array index. 另外请记住,您不能将其用作$value["id"]因为它的属性不是数组索引。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM