使用php转换数组数据

时间:2018-05-28 12:23:51

标签: php laravel

            [original:protected] => Array
                (
                    [user_id] => 65751
                    [social_id] => 
                    [parent_id] => 
                    [org_id] => 1
                    [type] => 3
                    [s_id] => 1
                    [role_id] => 0
                    [active] => 1
                    [name] => RX
                    [first_name] => JJ
                    [last_name] => DKL
                    [email] => first@testmail.com
                    [secondary_email] => 
                    [username] => cLvcyUr2

                )


    [1] => User Object

                (
                    [user_id] => 82197
                    [social_id] => 
                    [parent_id] => 
                    [org_id] => 1
                    [type] => 2
                    [s_id] => 1
                    [role_id] => 0
                    [active] => 1
                    [name] => sec
                    [first_name] => XX
                    [last_name] => J3
                    [email] => first@testmail.com
                    [secondary_email] => 
                    [username] => VfTqXyvJ

                )

如何转换数组数据意味着只保留两个电子邮件和用户名应该删除

Array (
[0] => Array (
    [email] => first@testmail.com
    [username] => cLvcyUr2
    )
[1] => Array (
    [email] => first@testmail.com
    [username] => VfTqXyvJ
    )
)

我怎么可能不会逐个取消数据,它应该自动取消设置并只选择两个值

3 个答案:

答案 0 :(得分:0)

为什么不创建一个空数组并只复制你需要的值?试图取消数组中的所有内容是很多工作,并且由于经验不够实际可维护。

请注意,您的粘贴代码同时包含数组和对象,但您的问题仅限于数组。

$newArray = [];

foreach ($oldArray as $item) {
    $newArray[] = [
        'email' => $item->email, 
        'username' => $item->username
    ]; // If $item is object
    $newArray[] = [
        'email' => $item['email'], 
        'username' => $item['username']
    ]; // If $item is array
}

var_dump($newArray);

答案 1 :(得分:0)

你有没有尝试过这样的事情:

$index = array_search('user_id', $array);
unset($array[$index]);

对要删除的所有密钥执行此操作。

答案 2 :(得分:0)

$newArray = [];

foreach ($oldArray as $item) {
$arr = [];
    $arr['email'] = $item->email;
    $arr['username'] = $item->username;

    $newArray[] = $arr;
}