2

How can I take an array with individual strings but also comma separated strings and explode the comma separated items into individual items? For instance:

while(($row =  mysql_fetch_array($downloads_query))) {
        $product_array[] = $row['product']; 
    }

$product_array[] returns:

item 1: "10003"
item 2: "10016"
item 3: "10008, 10007, 10010"

How can I split item 3 into individual items 3, 4 and 5 so that $product_array returns:

item 1: "10003"
item 2: "10016"
item 3: "10008"
item 4: "10007"
item 5: "10010"
NullPoiиteя
  • 56,591
  • 22
  • 125
  • 143
frankie
  • 661
  • 2
  • 10
  • 25
  • 4
    [**Please, don't use `mysql_*` functions in new code**](http://bit.ly/phpmsql). They are no longer maintained [and are officially deprecated](https://wiki.php.net/rfc/mysql_deprecation). See the [**red box**](http://j.mp/Te9zIL)? Learn about [*prepared statements*](http://j.mp/T9hLWi) instead, and use [PDO](http://php.net/pdo) or [MySQLi](http://php.net/mysqli) - [this article](http://j.mp/QEx8IB) will help you decide which. If you choose PDO, [here is a good tutorial](http://stackoverflow.com/questions/12859942/why-shouldnt-i-use-mysql-functions-in-php/14110189#14110189). – NullPoiиteя May 10 '13 at 06:04
  • Why you don't use explode function in php? – SAVAFA May 10 '13 at 06:06
  • @SaVaFa Yes, I know I have to use `explode`. But I am not sure how to implement it because doesn't `explode` return another array? Would I simply iterate over the exploded array and `push` to the original array? I assume there's a more elegant solution? – frankie May 10 '13 at 06:07

8 Answers8

5

explode() - PHP.net:

Explodes a string based on the given delimiter, result is an array. Worth mentioning: if there's not a single delimiter inside your string, it will still convert to an array like Array ( [0] => abc ). This means you don't even need to cast your items 1 and 2 to an array in order to allow array_merge() to function correctly.

array_merge() - PHP.net:

Merges multiple arrays into a new array.

$items = new array();
while(($row =  mysql_fetch_array($downloads_query))) {
    $items = array_merge($items, explode(',', $item3));
}
Menno
  • 12,175
  • 14
  • 56
  • 88
1
while(($row =  mysql_fetch_array($downloads_query))) {
        if(strpos($row['product'],',') > -1){
                $product_array += explode(',',$row['product']);
        } else {
                $product_array[] = $row['product']; 
        }
    }

Here is fast solution :) if there is comma it will explode it before adding it into your array.

  • As other people notice myslq_ functions are deprecated .. Better use mysqli or PDO instead :)
Svetoslav
  • 4,686
  • 2
  • 28
  • 43
1

You can try like this:

while(($row = mysql_fetch_array($downloads_query))) {
  if(strstr($row['product'], ',')) {
    $product_array = array_merge(explode(',',$row['product']), $product_array);
  } else {
   $product_array[] = $row['product'];
  } 
}
Tarun Singhal
  • 977
  • 8
  • 11
  • This is a code-only answer that does not employ best practice. See [the php manual Note](http://php.net/manual/en/function.strstr.php) that states using strstr() to check the existence of a substring is not efficient. As shown by other answers, no conditional is required at all; this means a second loss of efficiency due to unnecessary iterated function calls. – mickmackusa Oct 15 '17 at 02:25
0

You can user explode() function in php and the merge the return array into $product_array. somthing like this:

$product_array = array_merge(explode(',', $commaSeperatedArray), $product_array); 
hamedkh
  • 909
  • 3
  • 18
  • 35
0

The professional advice is to not do what you are doing. You should not be storing comma-separated values in table columns. These should be in their own table and JOINed when needed.

Anyhow, you can unconditionally explode and push the generated array into the perpetually flat result array using the spread operator (...).

Code: (Demo)

$array = [
    "10003",
    "10016",
    "10008, 10007, 10010",
];

$result = [];
foreach ($downloads_query as $row) {
    array_push($result, ...explode(', ', $row['product']));
}
var_export($result);

Output:

array (
  0 => '10003',
  1 => '10016',
  2 => '10008',
  3 => '10007',
  4 => '10010',
)

Alternatively, just join the strings with the same delimiting substring as the delimited values, then explode on that same delimiter. (Demo)

var_export(
    explode(', ', implode(', ', $array))
);
mickmackusa
  • 43,625
  • 12
  • 83
  • 136
-1

Untested, but here it goes.

function process_array($row)
{
    $result=array();
    $product=$row['product'];

    if(strpos($product, ',')!==false)
    {
        $result[]=explode(',', $product);
    }
    else
    {
        $result[]=$product;
    }

    return $result;
}

/////

$product_array=array();

while(($row =  mysql_fetch_array($downloads_query))) 
{
    $product_array=array_merge($product_array, proccess_array($row))
}

You get the idea...

The Marlboro Man
  • 971
  • 7
  • 22
-1

Make use of preg_split() instead of explode(). You can add any number of delimiters you want inside the function.

<?php
while(($row =  mysql_fetch_array($downloads_query))) {
        $string .= $row['product']." "; 
    }
    $product_array = preg_split( "/[;, ]/", $string);
?>
Shankar Narayana Damodaran
  • 68,075
  • 43
  • 96
  • 126
  • Why would you use `preg_split()`? There is not a single requirement mentioned that OP needs to split on multiple delimiters. – Menno May 10 '13 at 06:15
  • @Aquillo, What problem do you have with preg_split() ? It does return the same answer what the OP needs and this is pretty faster than your array_merge and explode as you are doing two operations. – Shankar Narayana Damodaran May 10 '13 at 06:33
  • You are appending "10003" "10016" (would become "1000310016") with eachother meaning there's no delimiter to split on? This code won't work. – Menno May 10 '13 at 06:40
  • You may want to append the space before `$row['product']` since this will still result in my earlier mentioned issue. Other than that, good solution. – Menno May 10 '13 at 07:13
-1
$format_Arr = array("test1","test2,test2.1","test3","test4,test5,test6,test7");
$formated_arr = array();
foreach($format_Arr as $arr){
$arr1 = explode(",",$arr);
if(count($arr1)>1){
    $formated_arr = array_merge($formated_arr,explode(',',$arr));
}else{
    $formated_arr[]= $arr;
}
}
print_r($formated_arr);
Anand
  • 1,011
  • 1
  • 9
  • 13