4

I have an array of objects and I need to convert to key value pairs, my code is

i have a model as: model setting.php

public function currency_info(){
     $currency_info = [
                ['code' => 'AED', 'name' => 'United Arab Emirates Dirham'],
                ['code' => 'ANG', 'name' => 'NL Antillian Guilder'],
                ['code' => 'ARS', 'name' => 'Argentine Peso'],
                ['code' => 'AUD', 'name' => 'Australian Dollar'],
                ['code' => 'BRL', 'name' => 'Brazilian Real'],
              ]
}

and controller as:

SettingController.php

public function index()
{
        $setting = new Setting();
        $currency_list = $setting->currency_info();

        $result = [];
        foreach ($currency_list as $currency) {
            $result[$currency->code] = $currency->name;
        }

        return $result;
}

i get the following error:

ErrorException (E_NOTICE) Trying to get property 'code' of non-object

Where am I doing wrong and how can I correct this?

2
  • Laravel has built in method to convert into array just use $setting->currency_info()->toArray(); Commented Aug 1, 2018 at 7:11
  • this doesnot work Commented Aug 1, 2018 at 7:17

3 Answers 3

9

As the data your trying to iterate over is an array (from an object) the notation should be...

$result[$currency['code']] = $currency['name'];

Or if you want a shorter version (depends on version of PHP), use array_column()...

$result = array_column($currency_list, 'name', 'code');
Sign up to request clarification or add additional context in comments.

3 Comments

$result[$currency['code']] = $currency['name']; works great, thank you for your answer
this is the best answer
It's annoying at times as people will downvote and not leave feedback. It's just something you will unfortunately have to get used to.
2
foreach ($currency_info as $currency) {
    $result[$currency['code']] = $currency['name'];
}

Comments

2

currency_info function return array, so treat it as array. You are using $currency->code to access code key from array, use as $currency["code"] instead.

public function index() {
    $setting = new Setting();
    $currency_list = $setting->currency_info();

    $result = [];
    foreach ($currency_list as $currency) {
        $result[$currency["code"]] = $currency["name"];
    }
    return $result;
}

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.