Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/arrays/13.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
在PHP中,如何计算多维数组中特定键的值?_Php_Arrays_Multidimensional Array - Fatal编程技术网

在PHP中,如何计算多维数组中特定键的值?

在PHP中,如何计算多维数组中特定键的值?,php,arrays,multidimensional-array,Php,Arrays,Multidimensional Array,我有一个如下所示的数组: 数组( [0]=>数组([city]=>309[商店]=>12[苹果]=>21[橙子]=>14[荔枝]=>34) [1] =>数组([城市]=>309[商店]=>13[苹果]=>0[橙子]=>11[荔枝]=>32) [2] =>数组([city]=>309[store]=>14[Apple]=>44[oranges]=>61[lichis]=>0) [3] =>数组([城市]=>309[商店]=>15[苹果]=>7[橙子]=>0[荔枝]=>6) [4] =>数组([城市

我有一个如下所示的数组:

数组(
[0]=>数组([city]=>309[商店]=>12[苹果]=>21[橙子]=>14[荔枝]=>34)
[1] =>数组([城市]=>309[商店]=>13[苹果]=>0[橙子]=>11[荔枝]=>32)
[2] =>数组([city]=>309[store]=>14[Apple]=>44[oranges]=>61[lichis]=>0)
[3] =>数组([城市]=>309[商店]=>15[苹果]=>7[橙子]=>0[荔枝]=>6)
[4] =>数组([城市]=>309[商店]=>16[苹果]=>0[橙子]=>0[荔枝]=>12) )

这里我需要做两件事:
1.获取城市中所有特定水果的数量(即309城市中总共有多少苹果、桔子、荔枝)和
2.如何获取特定商店的值


提前谢谢

好吧,假设数组名为$store

$count = 0;
$s = array();

foreach($store as $store){
 $count = 0;
 $count += $store['apples'];
 $count += $store['oranges'];

 $s[$store['store']] = $count;
}

如果需要,添加更多水果。

这是一个更复杂的示例,但比意大利面代码要好。首先将数组转换为XML

// this is your initial array
$my_array = array(
array("city"=>309, "store"=>12, "apples"=>21, "oranges"=>14, "lichis"=>34 ),
array("city"=>309, "store"=>13, "apples"=>0, "oranges"=>11, "lichis"=>32 ),
array("city"=>309, "store"=>14, "apples"=>44, "oranges"=>61, "lichis"=>0 ),
array("city"=>309, "store"=>15, "apples"=>7, "oranges"=>0, "lichis"=>6 ),
array("city"=>309, "store"=>16, "apples"=>0, "oranges"=>0, "lichis"=>12 ),
);
编写意大利面代码来手动隔离存储区会变成一个由if语句和循环组成的混乱丛林

// might as well convert it to xml
function array_to_xml( $data ) {
    $xml = "<xml>\n";
    foreach( $data as $row ) {
        $xml .= "<entry>";
        foreach( $row as $k => $v ) {
            $xml .= "<{$k}>{$v}</{$k}>";
        }
        $xml .= "</entry>\n";
    }
    $xml .= "</xml>\n";
    return( $xml );
}
现在,将其加载到可使用XPath(XML标准)查询的内容中:

$xml = simplexml_load_string( array_to_xml( $my_array ) );
要获得城市中所有特定水果的数量(即城市309中总共有多少苹果、桔子、荔枝),我们需要一个简单但可重用的汇总函数

// so lets make a generic function to count specific items
function count_items( $stores, $items = array() ) {
    $sum = array();
    foreach( $stores as $store ) {
        foreach( $items as $k ) {
            if( !isset( $sum[$k] ) ) $sum[$k] = 0;
            $sum[$k] += $store->$k;
        }
    }
    return( $sum );
}
我们只想要city 309,特别是苹果、桔子和地衣,因为它们是水果:

$only_this_city = $xml->xpath("//entry[city=309]");
print_r( count_items( $only_this_city, array("apples", "oranges", "lichis")) );
我们得到这个:

Array
(
    [apples] => 72
    [oranges] => 86
    [lichis] => 84
)
其次,要获取特定商店的值:

$only_this_store = $xml->xpath("//entry[city=309 and store=14]");
print_r( count_items( $only_this_store, array("apples") ) );
你会得到:

Array
(
    [apples] => 44
)
显然,您可以请求更多的项,或者更复杂的查询。在XPath上查找一些文档以备将来查询

function extractData( array $data, $store = null )
{
    $callback = function( $values, $array ) use ( $store )
    {
        // We require values for a particular store
        if( ! is_null( $store ) )
        {
            if( $array[ 'store' ] == $store )
            {
                return $array;
            }

            return false;
        }
        // Return the sum of all stores in a city
        else
        {
            // Toss out the city and store values since they're not needed
            unset( $array['city'], $array['store'] );

            // Seed the initial values
            if( ! is_array( $values ) || empty( $values ) )
            {
                return $array;
            }

            // array_map function used add the arrays
            $add = function( $a, $b )
            {
                return $a + $b;
            };

            // Add the arrays
            $summedArray = array_map( $add, $values, $array );

            // Return the combined array structure
            return array_combine( array_keys( $values ), $summedArray );
        }
    };

    return array_reduce( $data, $callback, array() );
}

$data = array(
    0 => array(
        "city" => 309,
        "store" => 12,
        "apples" => 21,
        "oranges" => 14,
        "lichis" => 34
    ),
    1 => array(
        "city" => 309,
        "store" => 13,
        "apples" => 0,
        "oranges" => 11,
        "lichis" => 32
    ),
    2 => array(
        "city" => 309,
        "store" => 14,
        "apples" => 44,
        "oranges" => 61,
        "lichis" => 0
    ),
    3 => array(
        "city" => 309,
        "store" => 15,
        "apples" => 7,
        "oranges" => 0,
        "lichis" => 6
    ),
    4 => array(
        "city" => 309,
        "store" => 16,
        "apples" => 0,
        "oranges" => 0,
        "lichis" => 12
    )
);

// Return the values for a particular store
print_r( extractData( $data, 16 ) );

// Return the total of all stores in the city
print_r( extractData( $data ) );
这将产生以下结果

单一城市

Array
(
    [city] => 309
    [store] => 16
    [apples] => 0
    [oranges] => 0
    [lichis] => 12
)
总计

Array
(
    [apples] => 72
    [oranges] => 86
    [lichis] => 84
)
注意:在做出任何反应之前……我知道OP没有询问如何以面向对象的方式处理这个问题,所以这只是一个建议

我将为整个数据创建一个单独的类,为每个存储数据创建另一个类

$arr = array(
    array('city' => 309, 'store' => 12, 'apples' => 21, 'oranges' => 14, 'lichis' => 34),
    array('city' => 309, 'store' => 13, 'apples' => 0, 'oranges' => 11, 'lichis' => 32),
    array('city' => 309, 'store' => 14, 'apples' => 44, 'oranges' => 61, 'lichis' => 0),
    array('city' => 309, 'store' => 15, 'apples' => 7, 'oranges' => 0, 'lichis' => 6),
    array('city' => 309, 'store' => 16, 'apples' => 0, 'oranges' => 0, 'lichis' => 12)
);

foreach ($arr as $rec) {
    $storeID = $rec['store'];
    $city = $rec['city'];
    unset($rec['city'],$rec['store']);
    // assuming all the keys except these 2
    // represent product name->quantity pairs
    StoreData::add(new Store($storeID,$city,$rec));
}
//print_r(StoreData::$stores);

echo
'<b>total products:</b> ' .
    StoreData::get_total_products() . PHP_EOL .
'<b>total products in city #309:</b> ' .
    StoreData::get_total_products_by_city(309) . PHP_EOL .
'<b>"apples" everywhere:</b> ' .
    StoreData::get_product_total('apples') . PHP_EOL .
'<b>"apples" in store #12:</b> ' .
    StoreData::get_product_total_by_store('apples',12) . PHP_EOL .
'<b>"apples" in city #309:</b> ' .
    StoreData::get_product_total_by_city('apples',309);


class StoreData {

    public static $stores = array();

    public static function add(Store $store) {
        self::$stores[] = $store;
    }

    public static function remove(Store $store) {
        foreach (self::$stores as $key => $value) {
            if ($value == $store) {
                unset(self::$stores[$key]);
                break;
            }
        }
    }

    public static function find_by_city($cityID) {
        $cityID = (int) $cityID;
        return array_filter(self::$stores,create_function(
            '$store',
            "return \$store->city == $cityID;")
        );
    }

    public static function find_by_store($storeID) {
        $storeID = (int) $storeID;
        foreach (self::$stores as $store) {
            if ($store->id == $storeID) return $store;
        }
        return FALSE;
    }

    public static function get_total_products() {
        $total = 0;
        foreach (self::$stores as $store)
            $total += $store->get_total_products();
        return $total;
    }

    public static function get_total_products_by_city($city) {
        $stores = self::find_by_city((int) $city);
        $total = 0;
        foreach ($stores as $store)
            $total += $store->get_total_products();
        return $total;
    }

    public static function get_product_total_by_city($productName,$city) {
        return self::product_total($productName,self::find_by_city((int) $city));
    }

    public static function get_product_total_by_store($productName,$storeID) {
        $res = self::find_by_store((int) $storeID);
        return $res ? self::product_total($productName,array($res)) : $res;
    }

    public static function get_product_total($productName) {
        return self::product_total($productName,self::$stores);
    }

    private static function product_total($productName,$stores=NULL) {
        $total = 0;
        foreach ($stores as $store)
            $total += $store->get_product_total($productName);
        return $total;
    }

}

class Store {

    public $id;
    public $city;
    public $products;

    function __construct($id,$city,$products=array()) {
        $this->id = $id;
        $this->city = $city;
        $this->products = $products;
    }

    public function get_total_products() {
        return array_sum($this->products);
    }

    public function get_product_total($productName) {
        if (isset($this->products[$productName]))
            return (int) $this->products[$productName];
        return 0;
    }

}
$arr=array(
数组('city'=>309,'store'=>12,'Apple'=>21,'oranges'=>14,'lichis'=>34),
数组('city'=>309,'store'=>13,'Apple'=>0,'oranges'=>11,'lichis'=>32),
数组('city'=>309,'store'=>14,'Apple'=>44,'oranges'=>61,'lichis'=>0),
数组('city'=>309,'store'=>15,'Apple'=>7,'oranges'=>0,'lichis'=>6),
数组('city'=>309,'store'=>16,'Apple'=>0,'oranges'=>0,'lichis'=>12)
);
foreach($arr作为$rec){
$storeID=$rec['store'];
$city=$rec['city'];
未设置($rec['city',$rec['store']);
//假设除了这两个键以外的所有键
//表示产品名称->数量对
StoreData::添加(新商店($storeID,$city,$rec));
}
//打印(存储数据:$stores);
回声
“总产品:”。
StoreData::get_total_products()。PHP_EOL。
“城市产品总量”309:”。
StoreData::按城市获取产品总数(309)。PHP_EOL。
到处都是苹果。
StoreData::获取产品总数(“苹果”)。PHP_EOL。
"苹果店#12:"。
StoreData::按商店(“苹果”,12)获取产品总数。PHP_EOL。
城市里的“苹果”。
StoreData::按城市(“苹果”,309)获取产品总量;
类存储数据{
公共静态$stores=array();
公共静态函数add(Store$Store){
self::$stores[]=$store;
}
公共静态函数删除(Store$Store){
foreach(self::$存储为$key=>$value){
如果($value==$store){
取消设置(self:$stores[$key]);
打破
}
}
}
公共静态函数按城市查找($cityID){
$cityID=(int)$cityID;
返回数组_过滤器(self::$stores,create_函数(
“$store”,
“return\$store->city==$cityID;”)
);
}
公共静态函数按存储查找存储($storeID){
$storeID=(int)$storeID;
foreach(self::$stores作为$store){
如果($store->id==$storeID)返回$store;
}
返回FALSE;
}
公共静态函数get_total_products(){
$total=0;
foreach(self::$stores作为$store)
$total+=$store->get_total_products();
返回$total;
}
公共静态函数按城市(城市)获取产品总数{
$stores=self::按城市查找城市((int)$city);
$total=0;
foreach($stores作为$store存储)
$total+=$store->get_total_products();
返回$total;
}
公共静态函数按城市获取产品总数($productName,$city){
返回self::product_总计($productName,self::按城市查找((int)$city));
}
公共静态函数按存储获取产品总数($productName,$storeID){
$res=self::按存储查找存储((int)$storeID);
返回$res?self::product_total($productName,array($res)):$res;
}
公共静态函数获取产品总数($productName){
返回self::product_总计($productName,self::$stores);
}
私有静态函数产品\总计($productName,$stores=NULL){
$total=0;
foreach($stores作为$store存储)
$total+=$store->get\u product\u total($productName);
返回$total;
}
}
班级商店{
公费$id;
公共城市;
公共产品;
函数构造($id,$city,$products=array()){
$this->id=$id;
$this->city=$city;
$this->products=$products;
}
公共函数获取总产品(){
返回数组的总和($this->products);
}
公用函数获取产品总数($productName){
如果(isset($this->products[$productName]))
返回(int)$this->products[$productName];
返回0;
}
}
将输出

产品总数:242
全市产品总量#309:242
到处都是苹果:72
商店里的“苹果”#12:21
城市中的“苹果”#3
$arr = array(
    array('city' => 309, 'store' => 12, 'apples' => 21, 'oranges' => 14, 'lichis' => 34),
    array('city' => 309, 'store' => 13, 'apples' => 0, 'oranges' => 11, 'lichis' => 32),
    array('city' => 309, 'store' => 14, 'apples' => 44, 'oranges' => 61, 'lichis' => 0),
    array('city' => 309, 'store' => 15, 'apples' => 7, 'oranges' => 0, 'lichis' => 6),
    array('city' => 309, 'store' => 16, 'apples' => 0, 'oranges' => 0, 'lichis' => 12)
);

foreach ($arr as $rec) {
    $storeID = $rec['store'];
    $city = $rec['city'];
    unset($rec['city'],$rec['store']);
    // assuming all the keys except these 2
    // represent product name->quantity pairs
    StoreData::add(new Store($storeID,$city,$rec));
}
//print_r(StoreData::$stores);

echo
'<b>total products:</b> ' .
    StoreData::get_total_products() . PHP_EOL .
'<b>total products in city #309:</b> ' .
    StoreData::get_total_products_by_city(309) . PHP_EOL .
'<b>"apples" everywhere:</b> ' .
    StoreData::get_product_total('apples') . PHP_EOL .
'<b>"apples" in store #12:</b> ' .
    StoreData::get_product_total_by_store('apples',12) . PHP_EOL .
'<b>"apples" in city #309:</b> ' .
    StoreData::get_product_total_by_city('apples',309);


class StoreData {

    public static $stores = array();

    public static function add(Store $store) {
        self::$stores[] = $store;
    }

    public static function remove(Store $store) {
        foreach (self::$stores as $key => $value) {
            if ($value == $store) {
                unset(self::$stores[$key]);
                break;
            }
        }
    }

    public static function find_by_city($cityID) {
        $cityID = (int) $cityID;
        return array_filter(self::$stores,create_function(
            '$store',
            "return \$store->city == $cityID;")
        );
    }

    public static function find_by_store($storeID) {
        $storeID = (int) $storeID;
        foreach (self::$stores as $store) {
            if ($store->id == $storeID) return $store;
        }
        return FALSE;
    }

    public static function get_total_products() {
        $total = 0;
        foreach (self::$stores as $store)
            $total += $store->get_total_products();
        return $total;
    }

    public static function get_total_products_by_city($city) {
        $stores = self::find_by_city((int) $city);
        $total = 0;
        foreach ($stores as $store)
            $total += $store->get_total_products();
        return $total;
    }

    public static function get_product_total_by_city($productName,$city) {
        return self::product_total($productName,self::find_by_city((int) $city));
    }

    public static function get_product_total_by_store($productName,$storeID) {
        $res = self::find_by_store((int) $storeID);
        return $res ? self::product_total($productName,array($res)) : $res;
    }

    public static function get_product_total($productName) {
        return self::product_total($productName,self::$stores);
    }

    private static function product_total($productName,$stores=NULL) {
        $total = 0;
        foreach ($stores as $store)
            $total += $store->get_product_total($productName);
        return $total;
    }

}

class Store {

    public $id;
    public $city;
    public $products;

    function __construct($id,$city,$products=array()) {
        $this->id = $id;
        $this->city = $city;
        $this->products = $products;
    }

    public function get_total_products() {
        return array_sum($this->products);
    }

    public function get_product_total($productName) {
        if (isset($this->products[$productName]))
            return (int) $this->products[$productName];
        return 0;
    }

}