Search code examples
arrayscodeignitermultidimensional-arraycodeigniter-2loadvars

How to break up a multidimensional array that has been loaded w/ load->vars()


This array was passed by $this->load->var($data) with some global variables. I need to extract the array below from the associative array that var has instantiated for me. That array currently looks like this: Notice the multidimensional array below.

 Dump => array(1) {
  [9] => array(1) {
    [0] => object(stdClass)#21 (8) {
      ["day"] => string(2) "09"
      ["eventContent"] => string(14) "slug ok"
      ["eventTitle"] => string(4) "Slug"
      ["id"] => string(1) "4"
      ["user"] => string(3) "CZL"
      ["user_id"] => string(1) "1"
      ["slug"] => string(4) "Slug"
      ["eventDate"] => string(10) "2013-07-09"
    }
  }
}

I need to convert it to look like this: Notice the single dimension array below.

Dump => array(1) {
  [0] => object(stdClass)#21 (7) {
      ["day"] => string(2) "09"
      ["eventContent"] => string(14) "slug ok"
      ["eventTitle"] => string(4) "Slug"
      ["id"] => string(1) "4"
      ["user"] => string(3) "CZL"
      ["user_id"] => string(1) "1"
      ["slug"] => string(4) "Slug"
      ["eventDate"] => string(10) "2013-07-09"
  }
}

Besides converting the multi to a single, is there a way I could call the singular array from the multidimensional one?

I am using a foreach on the multidimensional array, but it's outputting incorrectly. Here is what I'm using. calendars is the array above that i am passing to it.

foreach ($calendars as $calendar) {
        $url = calendar_link($calendar);
        $string .= '<li>';
        $string .= '<h3>' . anchor($url, e($calendar->eventTitle)) .  ' ›</h3>';
        $string .= '<p class="pubdate">' . e($calendar->eventDate) . '</p>';
        $string .= '</li>';
    }

function calendar_link($calendar){
return 'calendar/event/' . intval($calendar->id) . '/' . e($calendar->slug);
}

Solution

  • If the multidimensional array really looks exactly like your dump, then you should be able to do somthing like:

    $calendar_single = $calendars[9]; // I dont know why you get 9 as array key here?

    Then you should have an array with one object.

    If you want to reach the object directly, try this:

    $calendar_object = $calendars[9][0];

    And then you foreach should work:

    foreach ($calendar_object as $calendar) { ...

    Not the nicest solution and it wont work if your array key (9) will change..

    You could also try a more general solution that could work regardless of array key indexes:

    foreach($multi as $single){
        foreach($single as $object){
            foreach($object as $calendar){
                // YOUR CODE HERE
                calendar_link($calendar); // ETC…
            }       
        }
    }