开发者

Make array with arrays from a mysql query

开发者 https://www.devze.com 2023-04-10 10:49 出处:网络
Working on a e-shop, i must read from the DB the products that have productpack not null. productpack from the DB looks like this : 0141,3122,0104,0111,3114,0106,0117 .

Working on a e-shop, i must read from the DB the products that have productpack not null.

productpack from the DB looks like this : 0141,3122,0104,0111,3114,0106,0117 .

I'm trying to get all the DB items that have productpack set (not null), and make them into an array with arrays with those codes (0141,3122,0104,0111,3114,0106,0117).

function p_productpacks(){

    $productpacks = array();
    $pack = array();

    $q = mysql_query('SELECT productpack FROM products WHERE productpack <> "";');

    while($p = mysql_fetch_object($q)){

        $pack = explode(",", $p);

        $productpacks[开发者_StackOverflow社区] = $pack;

    }

    return $productpacks;

}   


You need to create an array otherwise, you're overwriting existing packs:

$pack = explode(",", $p->productpack);

$productpacks[] = $pack;

For more information read about array_pushDocs and PHP Arrays Docs (and mysql_fetch_objectDocs).


You can get all productpacks in a CSV array using:

$result = mysql_query("SELECT GROUP_CONCAT(productpack) as productpacks
                       FROM products WHERE productpack <> '' ");
if ($result) {
  $row = mysql_fetch_row($result);
  $productpacks_as_CSV_string = $row['productpacks'];
}

That way you only need to get one row out of the database, saving lots of time.

See: http://dev.mysql.com/doc/refman/5.0/en/group-by-functions.html#function_group-concat


mysql_fetch_object returns an object and can't be used with string processing.. if you definitely want to use this, you need to do something like:

$pack=explode(',',$p->productpack);
$productpacks[]=$pack

Or, to use a good old array instead:

while ($p = mysql_query($q))
{
    $pack = explode(",", $p['productpack']);
    $productpacks[] = $pack;
}
0

精彩评论

暂无评论...
验证码 换一张
取 消