0

how could I explode each elements in an array?

Array
(
    [0] => countryId:2, productId:1, status:1, pId:18, xId:pdgje5566
)

please see below for above array:

$searchfor = $xId;

header('Content-Type: text/plain');

$contents = file_get_contents($file);
$pattern = preg_quote($searchfor, '/');
$pattern = "/^.*$pattern.*\$/m";

// search, and store all matching occurences in $matches
if(preg_match_all($pattern, $contents, $matches)){

   print_r($matches[0]);
   //echo implode("\n", $matches[0]);

}

please advise, thanks.

2
  • 1
    Is each element in the array a string or is that JSON representation for a 2d array there? Also what do you want to split on? Commented Sep 25, 2012 at 9:13
  • @Sammaye data are get from text file Commented Sep 25, 2012 at 9:14

1 Answer 1

8
foreach ($array as &$value) {
  $arr = array();
  foreach (explode(', ', $value) as $el) {
     $ret = explode(':', $el);
     $arr[$ret[0]] = $ret[1];
  }
  $value = $arr;
}
Sign up to request clarification or add additional context in comments.

5 Comments

This answer is missing its educational explanation and is promoting the notion that dumping a snippet is enough effort to earn unicorn points.
@mickmackusa Yep, but this answer is answered at the dawn of time of stackoverflow, someone is just to want to get a runnable code snippet. And for such question itself, the code is just enough for the educational purpose :)
Yes, I realize that I am poking an old post. The "dawn of time" came 3/4 years earlier for Stack Overflow. Old code-only answers inspire new users to believe that new code-only answers are acceptable and gather unicorn points. By role modeling better posting practices, we encourage future improvement in the culture of posting with the intent to educate/empower not just the OP but thousands of researchers. I often use ancient pages to close new duplicates -- I can only do so in good faith when the old page is educational enough to resolve the new page.
It might just be easier to find another page that is demonstrating how to explode a string on two different delimiters and close this page as a duplicate of that one. There will be many to choose from.
@mickmackusa Nice point 👍🏻

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.