我正在使用PHP中的多维数组。我想检测是否存在类似的值,然后计算相似值的数量并输出结果。例如,给定以下数组:
$products =
Array
(
[0] => Array
(
[price] => 100
[product] => cloths
[qty] => 3
)
[1] => Array
(
[price] => 101
[product] => cloths
[qty] => 10
)
[2] => Array
(
[price] => 102
[product] => cloths
[qty] => 16
)
[3] => Array
(
[price] => 103
[product] => cloths
[qty] => 1
)
[4] => Array
(
[price] => 108
[product] => cloths
[qty] => 6
)
[5] => Array
(
[price] => 107
[product] => cloths
[qty] => 4
)
[6] => Array
(
[price] => 109
[product] => cloths
[qty] => 5
)
[7] => Array
(
[price] => 105
[product] => cloths
[qty] => 2
)
[8] => Array
(
[price] => 104
[product] => cloths
[qty] => 5
)
[9] => Array
(
[price] => 106
[product] => cloths
[qty] => 2
)
[10] => Array
(
[price] => 111
[product] => cloths
[qty] => 1
)
)
如何解决这个问题?
foreach ($products as $key => $product) {
$price = $product['price'];
//now using this price how can i get all keys which are equal to this price
}
修改 我试过这个但没有用
echo $key = array_search(100, array_column($products, 'price'));
答案 0 :(得分:0)
尝试以下内容:
$keys = array_keys(array_filter($product, function($val) {return $val['price'] == 100; })
答案 1 :(得分:0)
我会创建一个包含价格作为键和产品键的数组作为值:
int main()
{
std::srand(std::time(0));
using std::size_t;
const size_t N = 20000;
std::string alphabet("ACGT");
// stuff the ballot
std::vector<std::string> v(100, "CCGT");
// build a properly weighted alphabet string
// to give each letter equal chance of appearing
// in the final string
std::string weighted;
// This could be scaled down to make the weighted string much smaller
for(size_t i = 0; i < (N - 200) / 4; ++i) // already have 200 Cs
weighted += "C";
for(size_t i = 0; i < (N - 100) / 4; ++i) // already have 100 Ns & Gs
weighted += "GT";
for(size_t i = 0; i < N / 4; ++i)
weighted += "A";
size_t remaining = N - (v.size() * 4);
// add the remaining characters to the weighted string
std::string s;
for(size_t i = 0; i < remaining; ++i)
s += weighted[std::rand() % weighted.size()];
// add the random "4 char" sequences to the vector so
// we can randomly distribute the pre-loaded special "4 char"
// sequence among them.
for(std::size_t i = 0; i < s.size(); i += 4)
v.push_back(s.substr(i, 4));
// distribute the "4 char" sequences randomly
std::random_shuffle(v.begin(), v.end());
// rebuild string s from vector
s.clear();
for(auto&& seq: v)
s += seq;
std::cout << s.size() << '\n'; // should be N
}
现在,$prices = array();
foreach ($products as $key => $product) {
$prices[$product['price']][] = $key;
}
包含所有产品密钥的数组,其中price = 105(在具体示例中,它只有一个:$prices[105]
):
7