I have an array $categories
and I would like to check if either 'computers' or 'laptops' are in the array. I can do
我有一個數組$categories,我想檢查數組中是否有“計算機”或“筆記本”。我能做的
$terms = wp_get_post_terms($post_id, 'product_cat');
foreach ($terms as $term) {
$categories[] = $term->slug;
}
if (in_array( 'computers', $categories)) {
//run a lot of code
}
if (in_array('laptops', $categories)) {
//run a lot of code
}
but is there a way to combine with an OR so I don't have to write out the code twice?
但是有沒有一種方法可以與OR結合,這樣我就不用寫兩次代碼了?
something like
類似的
if ((in_array( 'computers', $categories)) OR (in_array('computers-he', $categories))) {
//run a lot of code
}
I tried it but it doesn't work I get.
我試過了,但效果不佳。
PHP Warning: in_array() expects parameter 2 to be array, null
PHP警告:in_array()期望參數2為數組,null
4
1. Define
1。定義
$categories = array();
before-
之前,
$terms = wp_get_post_terms( $post_id, 'product_cat' );
2. Use ||
like this:-
2。使用| |這樣的:-
if(in_array('computers',$categories) || in_array('laptops',$categories)) {
//run a lot of code
}
Now full code will be:-
現在完整的代碼將是:-
$categories= array();
$terms = wp_get_post_terms( $post_id, 'product_cat' );
foreach($terms as $term) {
$categories[] = $term->slug;
}
if(in_array('computers',$categories) || in_array('laptops',$categories)) {
//run a lot of code
}
0
a different approach:
一種不同的方法:
$terms = wp_get_post_terms($post_id, 'product_cat');
foreach ($terms as $term)
{
if(in_array($term->slug, ['computers', 'laptops']))
{
//run a lot of code
break; //run the code once
}
}
0
I usually do this:
我通常這樣做:
if (array_intersect($categories, ['computers', 'laptops'])) {
//run a lot of code
}
If one or both terms are in $categories
, it returns the array with those terms, if none are in it, it returns an empty array which is falsy.
如果一個或兩個術語都在$categories中,它返回帶有這些術語的數組,如果沒有,它返回一個空數組,這是假的。
0
From you question, I guess you need to run code if there is at least one term of particular category. In such case you can use array_reduce
and take advantage of short-circuit evaluation:
從您的問題中,我猜您需要運行代碼,如果至少有一個術語的特定類別。在這種情況下,您可以使用array_reduce並利用短路評估:
$criteria = [
'computers' => true,
'laptops' => true
];
$test = function ($carry, $term) use ($criteria) {
return $carry || isset($criteria[$term->slug]);
};
if (array_reduce($terms, $test, false)) {
echo 'Run a lot of code.';
}
Here is working demo.
這是演示工作。
本站翻译的文章,版权归属于本站,未经许可禁止转摘,转摘请注明本文地址:https://www.itdaan.com/blog/2017/07/21/72527d9e1744d073fc442dc2ae9438bf.html。