for reason have array of kind, , want extract 2 first part of each key,some of key contain 5 pieces of string separated ',' while other contain 2 pieces of string separated y ',' ex:
array ( 'kksgzgg , kdhdhk', 'jjj , jjd , jsjs , sjsj , jjsjs', 'kksksk , kdkdkk', 'jjj , jjd , jdjdjdj , jjd , jdjdjddj', 'jjj , jjd , jdjdj , jjsj , sjsjsj', 'jjj , jjd' ); i need result 2 elements in each key(separated comma):
array ( [0] => kksgzgg , kdhdhk [1] => jjj , jjd [2] => kksksk , kdkdkk [3] => jjj , jjd [4] => jjj , jjd [5] => jjj , jjd ) thank help
you can following functions:
implode— join array elements stringexplode— split string stringarray_slice— extract slice of array
example:
$newarray = array(); foreach ($oldarray $value) { $newarray[] = implode(',', array_slice(explode(',', $value, 3), 0, 2)); } print_r($newarray); output:
array ( [0] => kksgzgg , kdhdhk [1] => jjj , jjd [2] => kksksk , kdkdkk [3] => jjj , jjd [4] => jjj , jjd [5] => jjj , jjd ) explanation:
the code inside foreach can rewritten temp variables, makes easier understand what's happening. following code equivalent one-liner above:
$parts = explode(',', $value, 3); $subsetofparts = array_slice($parts, 0, 2); $gluedtogether = implode(',', $subsetofparts); $newarray[] = $gluedtogether; these 4 lines applied values in array 1 one during foreach. let's assume doing this $value:
'jjj , jjd , jsjs , sjsj , jjsjs' the first line split value comma. third argument 3 controls how many elements in $parts:
[0 => 'jjj ', [1] => ' jjd ', [2] => ' jsjs , sjsj , jjsjs'] the second line create new array $parts contains first , second elements, result be
[0 => 'jjj ', [1] => ' jjd '] the third line glue the subset of parts comma,
'jjj , jjd' that string added $newarray.
Comments
Post a Comment