-3

I have data string " Atap Bocor AC Bagus Kursi bagus Meja Bagus " I want convert to array:

array(0) => Atap Bocor
array(1) => AC Bagus
array(2) => Kursi bagus
array(3) => Meja Bagus

I try use php explode dan jquery split not work as i want

3 Answers3

2

Use regexp

function conver_to_array($str, $delim, $n)
{
  return array_map(function($p) use ($delim) {
      return implode($delim, $p);
  }, array_chunk(explode($delim, $str), $n));
}


$array = conver_to_array("Atap Bocor AC Bagus Kursi bagus Meja Bagus", " ", 2);
print_r($array);

DEMO

Dave
  • 3,046
  • 7
  • 19
  • 32
0

If its always pairs that you are after, split the string at the spaces and then create a new array by combining every two items and pushing that.

var str = "Atap Bocor AC Bagus Kursi bagus Meja Bagus";


var strArr = str.split(' ');
var newArr = [];

for(i=1; i<strArr.length; i+=2) {
  newArr.push(strArr[i-1] + ' ' +  strArr[i])
}

console.log(newArr); // gives ["Atap Bocor","AC Bagus", "Kursi bagus", "Meja Bagus"]
gavgrif
  • 14,151
  • 2
  • 21
  • 24
0

Thank you all, solved. I use code:

    function split_nth($str, $delim, $n)
{
  return array_map(function($p) use ($delim) {
      return implode($delim, $p);
  }, array_chunk(explode($delim, $str), $n));
}


$array = split_nth("Atap Bocor AC Bagus Kursi bagus Meja Bagus meja Rusak", " ", 2);
print_r($array);