I'm trying to create data save variable using a text file. I read that the collect function in laravel is the right choice for managing the data.
Here is the data saved after I exploded with PHP_EOL :
What I want to do is explode once more per array with "|", so my code is like this but it can't.
$temps=explode(PHP_EOL,$note);
$isi=collect([
explode('|',$temps)
]);
This code can only be applied if it is accompanied by a manual array like this :
$isi=collect([
explode('|',$temps[0]),
explode('|',$temps[2])
]);
Please help.
CodePudding user response:
As I think you've worked out, explode returns an array but accepts a string, so you can't pass the result of explode
directly to another explode
call.
Instead you need to get each individual string in the array produced by the first explode
, and explode
each one separately.
Clearly it's not practical to try and hard-code a reference to each item of the array (as per your attempt), so instead you can use a loop to fetch each item, or a slightly neater way is to use array_map, like in the following example:
function pipeExplode($str)
{
return explode("|", $str);
}
$text = "sdlkfjsdl|kwflwerflwekr|wlkjlgk4w\n3rtljhrfgkjed|3jhkrjghd|4t44thj\n33rtlhwege|3rth3herjgke|hkjfgdf";
$arr = explode(PHP_EOL, $text);
$finalArr = array_map('pipeExplode', $arr);
print_r($finalArr);
Demo: https://3v4l.org/EM6Ct
This will take each string from the first array, pass it through the pipeExplode
function to get a new array back from that, and then add that array back into the outer array which is returned by the array_map
function.