Removing selected elements from array of associative arrays

戏子无情 提交于 2019-12-12 01:32:49

问题


I have the following array of associative arrays.

$result = array(
    (int) 0 => array(
        'name' => 'Luke',
        'id_number' => '1111',
        'address' => '1544addr',
        'time_here' => '2014-04-12 13:07:08'
    ),
    (int) 1 => array(
        'name' => 'Sam',
        'id_number' => '2222',
        'address' => '1584addr',
        'time_here' => '2014-04-12 14:15:26'

I want to remove selected elements from this array such that it will look like this;

array(
    (int) 0 => array(
        'name' => 'Luke',
        'id_number' => '1111'
    ),
    (int) 1 => array(
        'name' => 'Sam',
        'id_number' => '2222',

This is the code I wrote;

    foreach($result as $value) 
    {            
        unset($value('address')  );
        unset($value('time_here')  );
    } 

When I run the code, Apache web server crashed.

Can the smarter members point out what did I do wrong? Thank you very much.


回答1:


Array notation is wrong, use this;

$finalResult = array();
foreach($result as $value) 
{            
    unset($value['address']  );
    unset($value['time_here']  );
    $finalResult[] = $value;
}

Here is a working demo: Demo




回答2:


That is because you are not accessing array correctly. Use square bracket insted of round brackets :

foreach($result as $value) 
    {            
        unset($value['address']  );
        unset($value['time_here']  );
    } 


来源:https://stackoverflow.com/questions/23235355/removing-selected-elements-from-array-of-associative-arrays

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!