Reputation: 2588
I have an array that is separated by "|". What I wanna do is separate by this identifier.
The array is as follows:-
myid1|My Title|Detailed Description
myid2|My Title|Second Row Description
myid3|My Title|Third row description
What I did was that I just used explode
on it to get my desired results.
$required_cells = explode('|', $bulk_array);
But the problem is (as shown below) that only my first array is properly exploded and the next first cell of the next array is mixed due to the "new line".
Is it possible that I can get the upper array in consecutive array cells?
Array
(
[0] => myid1
[1] => My Title
[2] => Detailed Description
myid2
[3] => My Title
[4] => Second Row Description
myid3
[5] => My Title
[6] => Second Row Description
)
Upvotes: 0
Views: 845
Reputation: 15783
You can use array_map
:
$str = "myid1|My Title|Detailed Description
myid2|My Title|Second Row Description
myid3|My Title|Third row description";
$newLine = (explode("\n", $str));
$temp = array();
$result = array_map(function($someStr) use(&$temp) {
$exploded = explode("|", $someStr);
foreach($exploded as $value) $temp[] = $value;
}, $newLine);
print_r($temp);
Sandbox example, if you don't need it flatten you can drop the foreach part:
$str = "myid1|My Title|Detailed Description
myid2|My Title|Second Row Description
myid3|My Title|Third row description";
$newLine = (explode("\n", $str));
$result = array_map(function($someStr) {
return explode("|", $someStr);
}, $newLine);
print_r($result);
Upvotes: 1
Reputation: 1769
Explode on newlines, aka "\n"
first, then loop through that array and explode on pipes, aka '|'
$bulk_array = "myid1|My Title|Detailed Description
myid2|My Title|Second Row Description
myid3|My Title|Third row description";
$lines = explode("\n", $bulk_array);
foreach ($lines as $key => $line)
{
$lines[$key] = explode('|', $line);
}
Then print_r($lines);
will output:
Array
(
[0] => Array
(
[0] => myid1
[1] => My Title
[2] => Detailed Description
)
[1] => Array
(
[0] => myid2
[1] => My Title
[2] => Second Row Description
)
[2] => Array
(
[0] => myid3
[1] => My Title
[2] => Third row description
)
)
Upvotes: 2
Reputation: 53841
You can use preg_split
to explode on |
and EOL:
$parts = preg_split('#(\||\r\n|\r|\n)#', $string); // EOL is actually 3 different types
Which makes 1 array with 9 elements.
Or first explode on EOL and then on |
:
$lines = preg_split('#(\r\n|\r|\n)#', $string);
$lines = array_map(function($line) {
return explode('|', trim($line));
});
Which makes 3 arrays with 3 elements each.
Upvotes: 2