算上类似数组的键 [英] Count Similar Array Keys
问题描述
我有一个POST请求来我的页面之一,这里是一小部分:
I have a POST request coming to one of my pages, here is a small segment:
[shipCountry] => United States
[status] => Accepted
[sku1] => test
[product1] => Test Product
[quantity1] => 1
[price1] => 0.00
这请求可以是任何尺寸,并且每个产品的名称和数量的主要会遇到的productN和quantityN,其中N是一个整数,从1开始。
This request can be any size, and each products name and quantity's key would come across as "productN" and "quantityN", where N is an integer, starting from 1.
我想可以算很多独特的钥匙怎么格式符合以上,这会给我多少产品被勒令(未明确请求给予号)的计数。
I would like to be able to count how many unique keys match the format above, which would give me a count of how many products were ordered (a number which is not explicitly given in the request).
什么是在PHP中做到这一点的最好方法是什么?
What's the best way to do this in PHP?
推荐答案
好吧,如果你知道,每款产品都会有相应的数组键匹配productN,你可以这样做:
Well, if you know that every product will have a corresponding array key matching "productN", you could do this:
$productKeyCount = count(preg_grep("/^product(\d)+$/",array_keys($_POST)));
preg_grep()在阵列非常适用于那种事。
preg_grep() works well on arrays for that kind of thing.
这篇关于算上类似数组的键的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!