Mukhila Asokan
Mukhila Asokan

Reputation: 653

Divide the array and create new array

I have array like this

array (size=6)
  0 => string '2      16     10     4      0      0      0      0      0'     
  1 => string '0      0      0      4' 
  2 => string '2      15     8      6      0      0      0      0      0' 
  3 => string '0      0      0      3' 
  4 => string '3      18     12     5      0      0      0      0      0' 
  5 => string '0      0      0      2'

I want to divide the array and create a new array like

array1 (size = 1)
0 => '2 16 10 4 0 0 0 0 0 0 0 0 0 4'

array2 (size = 1)
0 => '2 15 8 6 0 0 0 0 0 0 0 0 3'

array3 (size = 2)
0 => '3 18 12 5 0 0 0 0 0 0 0 0 2'

array_chunk() works fine. But it not supported my array

Upvotes: 0

Views: 67

Answers (3)

mickmackusa
mickmackusa

Reputation: 47904

Method #1: (Demo)

$prepped_copy=preg_replace('/\s+/',' ',$array);  // reduce spacing throughout entire array
while($prepped_copy){  // iterate while there are any elements in the array
    $result[]=implode(' ',array_splice($prepped_copy,0,2));  // concat 2 elements at a time
}

var_export($result);

Method #2 (Demo)

$pairs=array_chunk(preg_replace('/\s+/',' ',$array),2);  // reduce spacing and pair elements
foreach($pairs as $pair){
    $result[]="{$pair[0]} {$pair[1]}";  // concat 2 elements at a time
}

var_export($result);

Both Output:

array (
  0 => '2 16 10 4 0 0 0 0 0 0 0 0 4',
  1 => '2 15 8 6 0 0 0 0 0 0 0 0 3',
  2 => '3 18 12 5 0 0 0 0 0 0 0 0 2',
)

To my surprise, Method #1 was actually slightly faster using the small sample dataset (but not noticeably so).

Upvotes: 0

Death-is-the-real-truth
Death-is-the-real-truth

Reputation: 72299

You can do it through array_chunk() and foreach()

$new_array = array_chunk($original_array,2);

$final_array = [];

foreach($new_array as $arr){
 $final_array[] = $arr[0].' '.$arr[1];
}

print_r($final_array);

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

Note:- If you want to remove extra white-spaces in-between the strings, then use preg_replace()

$new_array = array_chunk($original_array,2);

$final_array = [];

foreach($new_array as $arr){
 $final_array[] = preg_replace('/\s+/', ' ', $arr[0]).' '.preg_replace('/\s+/', ' ', $arr[1]);
}

print_r($final_array);

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

Upvotes: 0

Sri Madhan
Sri Madhan

Reputation: 158

use array_chunk($array_name, 2)

the above will return a multi dimension array.

Upvotes: 1

Related Questions