Sign up ×
Stack Overflow is a question and answer site for professional and enthusiast programmers. It's 100% free.

I am new to PHP Codeigniter. I have a database inner join query in that I am fetching category id, category name, subcategory id and subcategory name as shown below.

e.g. http://i.stack.imgur.com/KbrkF.png

I am figuring out the way to create multidimensional array with category id, name and subcategories details as an in it.

e.g.

Array[0]=>Array ( [category_id] => 1 [category_name] => Computer [sub] => 
          Array ([0]=> [subcategory_id] => 1 [subcategory_name] => C Programming ) 
                 [1]=> [subcategory_id] => 2 [subcategory_name] => Website Development) 
                 [2]=> [subcategory_id] => 4 [subcategory_name] => Java)) 

Array[1]=>Array ( [category_id] => 2 [category_name] => Robotics [sub] => 
          Array ( [subcategory_id] => 3 [subcategory_name] => Robo Wars))

Thanks

share|improve this question
    
can you post the query? –  Nouphal.M Jan 20 '14 at 15:03

2 Answers 2

up vote 2 down vote accepted

Suppose the following is your result array from db

$queryResult = array(
  array('category_id'=>1,'category_name'=>'Computer','subcategory_id'=>1,'subcategory_name'=>'C Programming','category_id'=>'1'),
  array('category_id'=>1,'category_name'=>'Computer','subcategory_id'=>2,'subcategory_name'=>'Website Development','category_id'=>'1'),
  array('category_id'=>1,'category_name'=>'Computer','subcategory_id'=>4,'subcategory_name'=>'Java','category_id'=>'1'),
  array('category_id'=>2,'category_name'=>'Robotics','subcategory_id'=>3,'subcategory_name'=>'Robo Wars','category_id'=>'2'),
);

Then you could try

$result = array();
foreach($queryResult as $arr){
  $result[$arr['category_id']]['category_id']= $arr['category_id'];
  $result[$arr['category_id']]['category_name'] = $arr['category_name'];
  $result[$arr['category_id']]['sub'][]= array('subcategory_id'=>$arr['subcategory_id'],'subcategory_name'=>$arr['subcategory_name']);
}

Hope this is helpful

share|improve this answer
    
Thanks a lot. I was trying to solve this from last two days. You saved me. –  Chopra Jan 20 '14 at 17:07

You didn't post your query, but I'll assume it looks something like this;

$sql = 'SELECT whatever FROM my_table WHERE category = ?';

$data = array(
    $category
);

$query = $this->db
    ->query( $sql, $data )
    ->result_array();

Adding the ->result_array() function to your query will return an associative array instead of an object.

share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.