0

In my public function I created an array with two values type and id:

public function easypost_database()
        {

            \EasyPost\EasyPost::setApiKey('mykey');
            $cas = \EasyPost\CarrierAccount::all();
            foreach ($cas as $key => $value) {
                $this->services[] = array('type' => $value['type'],
                  'id'   => $value['id']
              );
            }

        }

My array looks like that:

Array
(
    [0] => Array
        (
            [type] => CanadaPostAccount
            [id] => myidcp0
        )

    [1] => Array
        (
            [type] => PurolatorAccount
            [id] => myidp0
        )

)

Now in my other function, I want to extract those values and echo them (Actually I want to insert those value in a dropdown, but for the sake of this question let's pretend that I will echo them).

so my other function looks like:

public function settings_form($current)
{
    $database = $this->easypost_database();
    $services_a = $this->services;

    foreach ($services_a as $key => $value) {

        foreach ($value['type'] as $key => $val) {
            print_r($val)
        }
    }
}

for some reason, I'm not able to print my array, because the array returns a null value (or just the first value of the array).

I can create an array and push my value there outside the foreach loop, but I was looking for a more elegant way to deal with my code.

UPDATE:

I can always do something like:

$services_a   = $this->services;

        $service_type = array();

        foreach ($services_a as $key => $value) {
            array_push($service_type, $value['type']);
        }

        foreach ($service_type as $val) {
            $s .= $this->formDropdown('service[]', $val, $this->settings['service']) . '&nbsp;' . $val . '<br>';
        }

But I was looking for shorter way.

1
  • $value['type'] is not an array, so you can't loop through it, try changing it to foreach($value as $subKey => $subValue) {} Commented Apr 20, 2018 at 14:29

1 Answer 1

1

Try this:

public function settings_form($current)
{
    $database = $this->easypost_database();
    $services_a = $this->services;

    foreach ($services_a as $key => $value) {

        foreach ($value as $key => $val) {
            if( $key == 'type' ){
                print_r($val);
            }
        }
    }
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

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