0

I have this php array $result2 that looks like this.

[
    (int) 0 => object(stdClass) {
        id => (int) 1
        username => 'asd'
        password => '123'
        fullname => 'asd'
        email_addr => '[email protected]'
    }
]

From $result2, I want to have a $json_result that looks like this;

[{"email_addr":"[email protected]"}]

I tried $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]

The output is like this which is wrong;

[{"email_addr":null}]

What is the correct way?

3
  • What line is line 126? Commented Sep 22, 2015 at 10:01
  • $emailAddress[] = ['email_addr' => $result2['email_addr'] ]; Commented Sep 22, 2015 at 10:03
  • That means your $result2['email_addr'] is blank first check it is not blank then perform rest operations Commented Sep 22, 2015 at 10:03

5 Answers 5

2

Read carefully (int) 0 => object(stdClass) It's an object, and this object is an element with index 0 of an array. So:

$emailAddress[] = ['email_addr' => $result2[0]->email_addr ];
Sign up to request clarification or add additional context in comments.

1 Comment

Correct answer! Thanks!
1

it's object you can't show value if using $result2['email_addr'] you should using this $result2->email_addr method

Comments

1

You have an object of type stdClass so you can't access directly to the field 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

Comments

1

Try this:

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

Comments

1

You can use array_intersect_key :

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

It useful when you need one or more key to find. It more saving time

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.