jjzjj

PHP:检查数组元素是否存在跳过一级

coder 2024-05-02 原文

我正在尝试检查一个数组元素是否已经存在,如果不存在,我需要创建一个只填充一个值并将第二个值设置为 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
    );
}

问题在于检查元素是否存在 if (!$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:检查数组元素是否存在跳过一级,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38063748/

有关PHP:检查数组元素是否存在跳过一级的更多相关文章

  1. ruby-on-rails - 如何验证 update_all 是否实际在 Rails 中更新 - 2

    给定这段代码defcreate@upgrades=User.update_all(["role=?","upgraded"],:id=>params[:upgrade])redirect_toadmin_upgrades_path,:notice=>"Successfullyupgradeduser."end我如何在该操作中实际验证它们是否已保存或未重定向到适当的页面和消息? 最佳答案 在Rails3中,update_all不返回任何有意义的信息,除了已更新的记录数(这可能取决于您的DBMS是否返回该信息)。http://ar.ru

  2. ruby-on-rails - 在 Ruby 中循环遍历多个数组 - 2

    我有多个ActiveRecord子类Item的实例数组,我需要根据最早的事件循环打印。在这种情况下,我需要打印付款和维护日期,如下所示:ItemAmaintenancerequiredin5daysItemBpaymentrequiredin6daysItemApaymentrequiredin7daysItemBmaintenancerequiredin8days我目前有两个查询,用于查找maintenance和payment项目(非排他性查询),并输出如下内容:paymentrequiredin...maintenancerequiredin...有什么方法可以改善上述(丑陋的)代

  3. ruby - 多次弹出/移动 ruby​​ 数组 - 2

    我的代码目前看起来像这样numbers=[1,2,3,4,5]defpop_threepop=[]3.times{pop有没有办法在一行中完成pop_three方法中的内容?我基本上想做类似numbers.slice(0,3)的事情,但要删除切片中的数组项。嗯...嗯,我想我刚刚意识到我可以试试slice! 最佳答案 是numbers.pop(3)或者numbers.shift(3)如果你想要另一边。 关于ruby-多次弹出/移动ruby​​数组,我们在StackOverflow上找到一

  4. ruby - 将数组的内容转换为 int - 2

    我需要读入一个包含数字列表的文件。此代码读取文件并将其放入二维数组中。现在我需要获取数组中所有数字的平均值,但我需要将数组的内容更改为int。有什么想法可以将to_i方法放在哪里吗?ClassTerraindefinitializefile_name@input=IO.readlines(file_name)#readinfile@size=@input[0].to_i@land=[@size]x=1whilex 最佳答案 只需将数组映射为整数:@land边注如果你想得到一条线的平均值,你可以这样做:values=@input[x]

  5. ruby - 检查 "command"的输出应该包含 NilClass 的意外崩溃 - 2

    为了将Cucumber用于命令行脚本,我按照提供的说明安装了arubagem。它在我的Gemfile中,我可以验证是否安装了正确的版本并且我已经包含了require'aruba/cucumber'在'features/env.rb'中为了确保它能正常工作,我写了以下场景:@announceScenario:Testingcucumber/arubaGivenablankslateThentheoutputfrom"ls-la"shouldcontain"drw"假设事情应该失败。它确实失败了,但失败的原因是错误的:@announceScenario:Testingcucumber/ar

  6. ruby - 通过 erb 模板输出 ruby​​ 数组 - 2

    我正在使用puppet为ruby​​程序提供一组常量。我需要提供一组主机名,我的程序将对其进行迭代。在我之前使用的bash脚本中,我只是将它作为一个puppet变量hosts=>"host1,host2"我将其提供给bash脚本作为HOSTS=显然这对ruby​​不太适用——我需要它的格式hosts=["host1","host2"]自从phosts和putsmy_array.inspect提供输出["host1","host2"]我希望使用其中之一。不幸的是,我终其一生都无法弄清楚如何让它发挥作用。我尝试了以下各项:我发现某处他们指出我需要在函数调用前放置“function_”……这

  7. ruby - 检查数组是否在增加 - 2

    这个问题在这里已经有了答案:Checktoseeifanarrayisalreadysorted?(8个答案)关闭9年前。我只是想知道是否有办法检查数组是否在增加?这是我的解决方案,但我正在寻找更漂亮的方法:n=-1@arr.flatten.each{|e|returnfalseife

  8. ruby - 检查方法参数的类型 - 2

    我不确定传递给方法的对象的类型是否正确。我可能会将一个字符串传递给一个只能处理整数的函数。某种运行时保证怎么样?我看不到比以下更好的选择:defsomeFixNumMangler(input)raise"wrongtype:integerrequired"unlessinput.class==FixNumother_stuffend有更好的选择吗? 最佳答案 使用Kernel#Integer在使用之前转换输入的方法。当无法以任何合理的方式将输入转换为整数时,它将引发ArgumentError。defmy_method(number)

  9. ruby-on-rails - 跳过状态机方法的所有验证 - 2

    当我的预订模型通过rake任务在状态机上转换时,我试图找出如何跳过对ActiveRecord对象的特定实例的验证。我想在reservation.close时跳过所有验证!叫做。希望调用reservation.close!(:validate=>false)之类的东西。仅供引用,我们正在使用https://github.com/pluginaweek/state_machine用于状态机。这是我的预订模型的示例。classReservation["requested","negotiating","approved"])}state_machine:initial=>'requested

  10. ruby - 如果指定键的值在数组中相同,如何合并哈希 - 2

    我有一个这样的哈希数组:[{:foo=>2,:date=>Sat,01Sep2014},{:foo2=>2,:date=>Sat,02Sep2014},{:foo3=>3,:date=>Sat,01Sep2014},{:foo4=>4,:date=>Sat,03Sep2014},{:foo5=>5,:date=>Sat,02Sep2014}]如果:date相同,我想合并哈希值。我对上面数组的期望是:[{:foo=>2,:foo3=>3,:date=>Sat,01Sep2014},{:foo2=>2,:foo5=>5:date=>Sat,02Sep2014},{:foo4=>4,:dat

随机推荐