简体   繁体   中英

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?

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); and unset($results[0]->sent_date) instead and it should work. 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.

Or removal of indexes is must required than use unset inside the foreach loop as:

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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