0

I had an array that is separated by "|". What I wanted do was to separate it 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 was that only my first array was properly exploded and the next first cell of the next array was mixed due to the "new line". Hence I couldn't use explode only.

To get the upper array in consecutive array cells as follows, I used the code below:- (with the help of this thread)

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
)

The working code:-

$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);

This worked perfectly but then the problem occured. This code works fine in PHP Version 5.4.10, but gives the following error in PHP Version 5.2.14. My dev server is 5.4.10 and unfortunately my production server is 5.2.14 therefore I need to fix this issue. The error is as follows:-

Parse error: syntax error, unexpected T_FUNCTION, expecting ')' in page.php on line 310

0

1 Answer 1

2

You need to explode twice!

$result=array();
$lines=explode("\n", $str);
foreach ($lines as $line) 
  $result[]=explode('|', $line);

Or to stay with one dimension:

$result=array();
$lines=explode("\n", $str);
foreach ($lines as $line) 
  $result=array_merge($result,explode('|', $line));
Sign up to request clarification or add additional context in comments.

1 Comment

Is it possible to get the array by exploding it once? So that it gives the same output of two dimensional array but with a different code?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.