Alex
Alex

Reputation: 7688

PHP use foreach multidimensional data outside it

Having this php code:

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

How can I fix this, or what I am doing wrong because $['data']['car'][...] returns only 1 item for url, title and img outside case "_cars": foreach... but inside it does returns all the data.

Edit: but I wonder why doing print_r($data) inside the foreach ($searchResults['_cars']['items']... loop returns all data and outside that foreach only 1?

Upvotes: 0

Views: 420

Answers (1)

swatkins
swatkins

Reputation: 13640

I'm not quite sure what you're wanting, but at first glance, it looks like each iteration is overwriting the actual value of the array key:

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

You need to create an iterator and use that:

$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++;
}

Upvotes: 5

Related Questions