1

Currently, I have a 2d array, which is basiccaly like this:

$oriArr = array(
  [0]=>array(
     '1'=>'a',
     '2'=>'b',
     '3-1'=>'c',
     '4-1'=>'d',
     '3-2'=>'c1',
     '4-2'=>'d1' 
  ),
  [1]=>array(
     '1'=>'a',
     '2'=>'b',
     '3-1'=>'c',
     '4-1'=>'d',
     '3-2'=>'c1',
     '4-2'=>'d1', 
     '3-3'=>'c2',
     '4-3'=>'d2'
  ),
);

I want to split the array into 3d array by adding a new element like this:

$resArr= array(
      [0]=>array(
         [1]=>'a',
         [2]=>'b',
         ['items']=>array(
           [1]=>array(
              '3-'=>'c',
              '4-'=>'d',
           ),
           [2]=>array(
              '3-'=>'c1',
              '4-'=>'d1',
            )
         ),        
      ),
      [0]=>array(
         [1]=>'a',
         [2]=>'b',
         ['items']=>array(
           [1]=>array(
              '3-'=>'c',
              '4-'=>'d',
           ),
           [2]=>array(
              '3-'=>'c1',
              '4-'=>'d1',
            ),
           [3]=>array(
              '3-'=>'c2',
              '4-'=>'d2',
            )
         ),        
      ),
    );

I tried to split all the keys with '-' and add them to another array, but I dont know how to add a new element called 'items' and insert the values into it.

foreach($oriArr as $lines){            
   foreach($lines as $keys){
     $keyArr= array();                   
     if (strpos($keys, '-') !== false) {
           $keyArr[] = $keys;
     } 
   }             
}  

Is there any way that I can split my original array? Any answer would be appreciated!

1
  • Yeah thanks I missed it. Edited! Commented Sep 13, 2017 at 1:54

1 Answer 1

1

You have to do it like below:-

$final_array = array();
foreach($oriArr as $key=>$oriAr){
  $items  = array();
  foreach($oriAr as $k=>$oriA){
      $exploded_key = explode('-',$k);
      if(count($exploded_key) ==2){
         $items['items'][$exploded_key[1]][$exploded_key[0].'-'] = $oriA;
      }else{
       $items[$k]=$oriA;
      }
  }
  $final_array[$key] = $items;
}

print_r($final_array);

Output:-https://eval.in/860368

Sign up to request clarification or add additional context in comments.

2 Comments

Thank you a lot. It worked. I am pretty new to multi-dimensional array.
@Tedxxxx glad to help you :):)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.