大佬教程收集整理的这篇文章主要介绍了PHP:检查数组元素是否存在跳过一级,大佬教程大佬觉得挺不错的,现在分享给大家,也给大家做个参考。
我正在尝试检查数组元素是否已经存在,如果不存在,则需要创建一个数组元素,其中只填充一个值,第二个值设置为null.增加的复杂性是,我需要在检查数组时忽略第二级,而不必再次遍历数组,因为它可能是一个很大的数组.
我的数组如下所示:
Array
(
[2016-05-28] => Array
(
[0] => Array
(
[store] => 1
[price] => 12
)
[1] => Array
(
[store] => 7
[price] => 18
)
[2] => Array
(
[store] => 9
[price] =>
)
)
)
我试图检查是否存在一个具有存储值x的现有元素,如果不存在,则创建一个新元素,如果确实存在,则忽略它并继续前进.
对于此示例,我已经硬编码了$day和$store变量,但是通常将其填充在for循环中,然后下面的代码片段将在for循环内运行.
我的代码:
$day = '2016-05-28';
$store = 8;
if (!$historY[$day][][$store]) {
$historY[$day][] = array(
"store" => $store
, "price" => null
);
}
问题在于检查元素是否存在,如果(!$history [$day] [] [$store]){,是否有可能忽略$day元素和$store元素之间的第二级,以便检查store元素看它是否存在,我可以使用通配符还是in_array可以工作?
$setPriceHistoryData = $daoObj->getSetPriceHistoryData($set['id']);
$chartDays = date('Y-m-d', strtotime('-30 days'));
$priceHistoryData = array();
$endDay = date('Y-m-d');
while ($chartDays <= $endDay) {
for ($i = 0; $i < count($setPriceData["price_history_store_data"]); $i++) {
for ($j = 0; $j < count($setPriceHistoryData); $j++) {
if ($setPriceData["price_history_store_data"][$i]["id"] == $setPriceHistoryData[$j]["vph_store"]
&& $chartDays == $setPriceHistoryData[$j]["vph_date"]) {
$priceHistoryData[$chartDays][] = array(
"store" => $setPriceHistoryData[$j]["vph_store"]
, "price" => $setPriceHistoryData[$j]["vph_price"]
);
} else {
if (!$priceHistoryData[$chartDays][]["store"]) {
$priceHistoryData[$chartDays][] = array(
"store" => $setPriceHistoryData[$j]["vph_store"]
, "price" => null
);
}
}
}
}
// Increment day
$chartDays = date('Y-m-d', strtotime("+1 day", strtotime($chartDays)));
}
解决方法:
我会遍历所有日期.每天循环浏览您希望找到的所有商店编号.使用array_filter查找所需的存储.如果找不到所需的商店,请添加它.
$required_stores = [1,2,3,4]; // stores you wish to add if missing
$source = [
'2016-06-15'=>[
['store'=>1,'price'=>10],['store'=>2,'price'=>10],
],
'2016-06-16'=>[
['store'=>1,'price'=>10],['store'=>3,'price'=>10],
],
'2016-06-17'=>[
['store'=>3,'price'=>10],['store'=>4,'price'=>10],
],
];
//go through all dates. Notice we pass $stores as reference
//using "&" This allows us to modify it in the forEach
foreach ($source as $date => &$stores):
foreach($required_stores as $lookfor):
//$lookfor is the store number we want to add if it's missing
//will hold the store we look for, or be empty if it's not there
$found_store = array_filter(
$stores,
function($v) use ($lookfor){return $v['store']===$lookfor;}
);
//add the store to $stores if it was not found by array_filter
if(empty($found_storE)) $stores[] = ['store'=>$lookfor,'price'=>null];
endforeach;
endforeach;
// here, $source is padded with all required stores
以上是大佬教程为你收集整理的PHP:检查数组元素是否存在跳过一级全部内容,希望文章能够帮你解决PHP:检查数组元素是否存在跳过一级所遇到的程序开发问题。
如果觉得大佬教程网站内容还不错,欢迎将大佬教程推荐给程序员好友。
本图文内容来源于网友网络收集整理提供,作为学习参考使用,版权属于原作者。
如您有任何意见或建议可联系处理。小编QQ:384754419,请注明来意。