php - Merging two elements in array, if the next array element contains part of word -
ok, have array constructed \n seperated list. after slicing , dicing have got array way want except array has 2 elements should 1 (the array dynamic).
array (size=9) 0 => string 'bmc305' 1 => string '14:15' 2 => string 'onedata' //this should in same element 3 => string 'seconddata' //as one. 4 => string ' ' 5 => string 'bmc305' 6 => string '14:15' 7 => string 'onlydata' //here there 1 it's fine. 8 => string ' ' element [4] , [8] (the element following) changes alot first word each senario same. there methode or function can check elements if first letter/number of string "something"?
sorry if i'm writing in confusing way! i'm pretty confused right :p
thanks wants give shot.
there not 1 ready function. use array_filter find array keys startpoints are. next chunk splice.
<?php $array1 = array( 0 => 'bmc305', 1 => '14:15', 2 => 'onedata', 3 => 'seconddata', 4 => ' ', 5 => 'bmc305', 6 => '14:15', 7 => 'onlydata', 8 => ' '); function findstartelement($var) { return strpos($var, 'bmc') === 0; } $startelements = array_filter($array1, 'findstartelement'); $chunks = array(); $previouskey = null; foreach ($startelements $key => $value) { if ($previouskey !== null) { $chunks[] = array_splice($array1, $previouskey, $key - $previouskey); } $previouskey = $key; } // remaining part. $chunks[] = $array1; var_dump($chunks); ?> also, should use php 5.3, can real neat things here closure.
<?php function chunkbyvalue($array, $value) { $startelements = array_filter($array, function ($var) use ($value) { return strpos($var, $value) === 0; }); $chunks = array(); $previouskey = null; foreach ($startelements $key => $value) { if ($previouskey !== null) { $chunks[] = array_splice($array, $previouskey, $key - $previouskey); } $previouskey = $key; } // remaining part. $chunks[] = $array; return $chunks; } $array1 = array( 0 => 'bmc305', 1 => '14:15', 2 => 'onedata', 3 => 'seconddata', 4 => ' ', 5 => 'bmc305', 6 => '14:15', 7 => 'onlydata', 8 => ' '); var_dump(chunkbyvalue($array1, 'bmc')); ?>
Comments
Post a Comment