从Controller中的多个数组获取数据

时间:2019-12-07 21:48:35

标签: php arrays

我的国家/地区列表中有多个数组,例如:

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

但是当我为数组做foreach时,我得到了:

//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;

但是我得到这样的东西:

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,不是Belgija和阿根廷 没有好的国家,也没有我想要的数据。该如何解决?

2 个答案:

答案 0 :(得分:1)

您可以使用此foreach循环遍历另一个数组,并在数字匹配时交换字符串:

$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

答案 1 :(得分:0)

数组中的索引为0-based,这意味着:

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

必须成为

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

与国家/地区ID相关联。否则,它永远是一次性的。这是假定id始终按从最小到最大的顺序排列,并且所有id都是连续范围。