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.

conmen
  • 2,377
  • 18
  • 68
  • 98

1 Answers1

8
foreach ($array as &$value) {
  $arr = array();
  foreach (explode(', ', $value) as $el) {
     $ret = explode(':', $el);
     $arr[$ret[0]] = $ret[1];
  }
  $value = $arr;
}
mickmackusa
  • 43,625
  • 12
  • 83
  • 136
xdazz
  • 158,678
  • 38
  • 247
  • 274
  • This answer is missing its educational explanation and is promoting the notion that dumping a snippet is enough effort to earn unicorn points. – mickmackusa Jul 30 '21 at 14:51
  • @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 :) – xdazz Aug 04 '21 at 03:03
  • 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. – mickmackusa Aug 04 '21 at 03:07
  • 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 Aug 04 '21 at 03:08
  • @mickmackusa Nice point – xdazz Aug 04 '21 at 03:14