PHP使用foreach多维数据

时间:2012-01-26 16:51:36

标签: php codeigniter multidimensional-array foreach

有这个PHP代码:

$data['items'] =  array('cars', 'bikes', 'trains');
$data['title']   = $parameters['title'];

foreach ($searchResults as $key => $value)
{
    switch ($key)
    {
        case "_cars":
        foreach ($searchResults['_cars']['items'] as $car)
        {
            preg_match('@video/([^_]+)_([^/]+)@', $car['url'], $match);
            $url = $match[1].'/'.$match[2];
            $url = base_url().'video/'.substr($url,0,1).'d'.substr($url,1);

            $data['data']['car']['url']   = $url;
            $data['data']['car']['title'] = $car['title'];
            $data['data']['car']['img']   = $car['thumbnail_medium_url'];
        }
        break;
        // ................

我如何解决这个问题,或者我做错了什么因为$['data']['car'][...]仅在case "_cars": foreach...之外为url,title和img返回1项,但在其中返回所有数据。

编辑: 但我想知道为什么在foreach ($searchResults['_cars']['items']...循环中执行print_r($ data)会返回所有数据,而foreach之外只返回1?

1 个答案:

答案 0 :(得分:5)

我不太确定你想要什么,但乍一看,看起来每次迭代都会覆盖数组键的实际值:

$data['data']['car']['url'] = $url; // this is overwritten each time

您需要创建一个迭代器并使用它:

$i = 0;
foreach ($searchResults['_cars']['items'] as $car)
{
  preg_match('@video/([^_]+)_([^/]+)@', $car['url'], $match);
  $url = $match[1].'/'.$match[2];
  $url = base_url().'video/'.substr($url,0,1).'d'.substr($url,1);

  $data['data']['car'][$i]['url']   = $url;
  $data['data']['car'][$i]['title'] = $car['title'];
  $data['data']['car'][$i]['img']   = $car['thumbnail_medium_url'];
  $i++;
}