1

I have country list in array with multiple array, like:

public static function listCountries()
    {
        $this->country = array(
            array(1, 'SAD', 'sad.png'),
            array(2, 'Argentina', 'argentina.png'),
            array(3, 'Australija', 'australija.png'),
            array(4, 'Novi Zenland', 'noviz.png'),
            array(5, 'Belgija', 'belg.png'),
            array(6, 'Nizozemska', 'nizozemska.png')
        );
    }

But when i do foreach for array, i'm getting this:

//From DB
    $item->country = "1,4";

    $item->country = explode(",", $item->country);

    for($i=0; $i < count($item->country); $i++) {
        $index = $item->country[$i];

        if( !empty($this->country[$index]) ) {
            $item->country[$i] = $this->country[$index];
        }
    }

    $item->country = implode(",", $item->country);

    echo $item->country;

But i'm getting something like this:

array:2 [▼
  0 => array:3 [▼
    0 => 5
    1 => "Belgija"
    2 => "belg.png"
  ]
  1 => array:3 [▼
    0 => 2
    1 => "Argentina"
    2 => "argentina.png"
  ]
]

1 = SAD, 4 = Novi Zenland, not Belgija and Argentina There is no good country, also no data what i want. How to fix this?

2 Answers 2

1

You can use this foreach loop to go through the other array and swap the string if the number matches:

$item->country = "1,4";

$item->country = explode(",", $item->country);

for($i=0; $i < count($item->country); $i++) {
    $index = $item->country[$i];

    foreach($this->country as $c) {
        if($c[0] == $index) {
            $item->country[$i] = $c[1];   // or $item->country[$i] = $c; if you want all three items
            break;
        }
    }
}

$item->country = implode(",", $item->country);

echo $item->country;
// Should output: SAD,Novi Zenland
Sign up to request clarification or add additional context in comments.

1 Comment

I did it with small changes, there where is $item['country'][$i] i change this to $item->country[$i]. Can you edit post so i can vote for Answer? Thank you for all, Ivan :)
0

The indexes in arrays are 0-based, which means that:

$index = $item->country[$i];

Has to become

$index = $item->country[$i - 1];

To correlate with the country ids. Otherwise, it is always one off. This is assuming that the ids are always ordered from least to greatest, and all ids are a continuous range.

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.