English 中文(简体)
如何通过价值变化将一个阵列分为一个钥匙?
原标题:How to split an array via value change on one of the keys?
  • 时间:2011-10-13 11:58:01
  •  标签:
  • php
  • arrays

我从一个数据库中收回了几行,并从另一个桌子上合并,以获得每个产品的品牌。

Array(
    [0] => stdClass Object
        (
            [pid] => 1
            [prodref] => F50
            [brand] => 1
            [name] => Adidas
        )

    [1] => stdClass Object
        (
            [pid] => 3
            [prodref] => Mercurial
            [brand] => 2
            [name] => Nike
        )
)

这是一个简化版本,但我有4个品牌,在数据库中,我通过品牌订购了prodref,因此,我希望能够在brand之前将阵列分开。 关键——因此,我只能用一个数据库查询,在网页的不同地区展示所有阿达尼语产品。

问题回答
foreach ($rows as $row) {
    $result[$row->name][] = $row;
}

如果你只有非常具体的案例,就像内部财产具有像品牌2这样的价值,那么你就可以超负荷使用,然后按照你的看法加以使用:

# $rows is your resultset
$rows = function($filter = NULL, $prop =  brand ) use ($rows)
{
    if(!$filter) return $rows;
    $subset = array();
    foreach($rows as $row)
        if ($row->$prop == $filter) $subset[] = $row;
    return $subset;
};

如果你后来想产出所有<代码> 浏览量:

foreach($rows() as $row) ...

或者,如果你想获得所有品牌:

foreach($rows(2) as $row) ...

foreach($rows(1) as $row) ...

最后,如果你想获得其他一些财产:

foreach($rows( Adidas ,  name ) as $row) ...

如果您的申请不断增加,请查看。 SPL and the Iterators it provide.





相关问题
Brute-force/DoS prevention in PHP [closed]

I am trying to write a script to prevent brute-force login attempts in a website I m building. The logic goes something like this: User sends login information. Check if username and password is ...

please can anyone check this while loop and if condition

<?php $con=mysql_connect("localhost","mts","mts"); if(!con) { die( unable to connect . mysql_error()); } mysql_select_db("mts",$con); /* date_default_timezone_set ("Asia/Calcutta"); $date = ...

定值美元

如何确认来自正确来源的数字。

Generating a drop down list of timezones with PHP

Most sites need some way to show the dates on the site in the users preferred timezone. Below are two lists that I found and then one method using the built in PHP DateTime class in PHP 5. I need ...

Text as watermarking in PHP

I want to create text as a watermark for an image. the water mark should have the following properties front: Impact color: white opacity: 31% Font style: regular, bold Bevel and Emboss size: 30 ...

How does php cast boolean variables?

How does php cast boolean variables? I was trying to save a boolean value to an array: $result["Users"]["is_login"] = true; but when I use debug the is_login value is blank. and when I do ...

热门标签