user6818018
user6818018

Reputation:

Reassign value from an array in a foreach loop in object oriented php

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.

Upvotes: 0

Views: 73

Answers (1)

Yamu
Yamu

Reputation: 1662

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);
            }
        }
    }
}

Upvotes: 1

Related Questions