简体   繁体   English

从此php数组中检索单个值

[英]Retrieve single value from this php array

I have this php array $result2 that looks like this. 我有这个看起来像这样的php数组$result2

[
    (int) 0 => object(stdClass) {
        id => (int) 1
        username => 'asd'
        password => '123'
        fullname => 'asd'
        email_addr => 'asd@gmail.com'
    }
]

From $result2 , I want to have a $json_result that looks like this; $result2 ,我想要一个看起来像这样的$json_result ;

[{"email_addr":"asd@gmail.com"}]

I tried $emailAddress[] = ['email_addr' => $result2['email_addr'] ]; echo json_encode($emailAddress); 我试过$emailAddress[] = ['email_addr' => $result2['email_addr'] ]; echo json_encode($emailAddress); $emailAddress[] = ['email_addr' => $result2['email_addr'] ]; echo json_encode($emailAddress);

However, the error I get is this; 但是,我得到的错误是这样;

Notice (8): Undefined index: email_addr [APP/Controller\\DeptUsersController.php, line 126] 注意(8):未定义索引:email_addr [APP / Controller \\ DeptUsersController.php,第126行]

The output is like this which is wrong; 这样的输出是错误的。

[{"email_addr":null}]

What is the correct way? 正确的方法是什么?

Read carefully (int) 0 => object(stdClass) It's an object, and this object is an element with index 0 of an array. 仔细阅读(int) 0 => object(stdClass)这是一个对象,并且该对象是数组索引为0的元素。 So: 所以:

$emailAddress[] = ['email_addr' => $result2[0]->email_addr ];

如果使用$result2['email_addr']应该使用此$result2->email_addr方法,则该对象将无法显示值

You have an object of type stdClass so you can't access directly to the field email_addr . 您有一个stdClass类型的object ,因此您无法直接访问字段email_addr Try this code: 试试这个代码:

$mObject = new stdClass();
$mObject = $result2[0];
$emailAddress[] = ['email_addr' => $mObject->email_addr ];
echo json_encode($emailAddress);

This should fix your error 这应该可以解决您的错误

尝试这个:

$emailAddress[] = ['email_addr' => $result2[0]->email_addr ];

You can use array_intersect_key : 您可以使用array_intersect_key

$wanted = ["email_addr"=>""];
$data = [
    "id" => 1,
    "username" => 'asd',
    "password" => '123',
    "fullname" => 'asd',
    "email_addr" => 'asd@gmail.com',
];
$result = array_intersect_key($wanted, $data);
var_dump($result);

It useful when you need one or more key to find. 当您需要一个或多个键来查找时,它很有用。 It more saving time 节省更多时间

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

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