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

时间:2016-06-27 21:44:48

标签: php arrays

我正在尝试检查数组元素是否已经存在,如果不存在,我需要创建一个数组元素,只填充一个值,第二个值设置为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元素之间的第二级,以便它检查{{1} 1}}元素,看看它是否存在,我可以使用外卡还是会store工作?

这是我目前正在使用的完整代码。

in_array

6 个答案:

答案 0 :(得分:2)

我会遍历所有日期。对于每一天,循环遍历您希望找到的所有商店编号。使用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

答案 1 :(得分:2)

正如Rizier123建议的那样,你可以使用array_column()。 Yous可以编写一个简单的函数来接受存储数,通过引用和日期接受历史数组:

var outerObj = {

  nestedObj: {
    nestedObjMethod: function(key) {
      var URLS = {
        'url1': 'http://foo.com',
        'url2': 'http://bar.com',
        'url3': 'http://yay.com'
      };
      return URLS[key];
    }
  }
};

console.log(outerObj.nestedObj.nestedObjMethod('url1'));

答案 2 :(得分:0)

<?php
$history = array();    // Assuming that's array's identifier.
$history['2016-05-28'] = array (
    array('store' => 1, 'price' => 12),
    array('store' => 7, 'price' => 18),
    array('store' => 9, 'price' => 20)
);
// variables for the if condition
$day = '2016-05-28';
$store = 8;
$match_found = FALSE;

foreach($history[$day] as $element) {
    if ($element['store'] == $store) {
        $match_found = TRUE;
    }
    else {
        continue;
    }
}

if ($match_found == TRUE) {
    // I included a break statement here. break works only in iterations, not conditionals. 
} else {
    array_push($history[$day], array('store' => $store, 'price' => null));
    // I was pushing to $history[$date] instead of $history[$day] since the variable I created was $day, NOT $date
}

我重写了PHP代码段,因为键值声明给出了一些错误。例如,2016-05-28键元素应该是字符串或整数,根据PHP规范(http://php.net/manual/en/language.types.array.php)。所以你的代码片段就像上面的代码一样。

我编辑了代码,将数据附加到主日期元素而不是根

答案 3 :(得分:0)

一些嵌套循环应该这样做,我认为你可能想要创建一个新的日期元素,如果它在历史中也不存在。

代码被评论:

<?php
$history = Array
(
    '2016-05-28' => Array
    (
        0 => Array
        (
            'store' => 1,
            'price' => 12
        ),
        1 => Array
        (
            'store' => 7,
            'price' => 18
        ),
        2 => Array
        (
            'store' => 9,
            'price' => null
        )
    )
);

print_r($history);

$day = '2016-05-28';
$store = 8;

// loop through dates
foreach ($history as $key=>&$date){

  // scan for date
  $found_date = false;
  if ($key != $day) continue;
  $found_date = true;

  // scan for store
  foreach ($date as $item){
    $found_store = false;
    if ($item['store'] != $store) continue;
    $found_store = true;
    // stop looping if store found
    break;
  }

  // create null element
  if (!$found_store) {
      $date []= array(
          "store" => $store
          , "price" => null
      );
  }

  // stop looping if date found
  break;

}

// if date not found, create all elements
if (!$found_date) {
  $history[$day]= array(
    0 => array(
      "store" => $store
      , "price" => null
    )
  );
}

print_r($history);

在:

Array
(
    [2016-05-28] => Array
        (
            [0] => Array
                (
                    [store] => 1
                    [price] => 12
                )

            [1] => Array
                (
                    [store] => 7
                    [price] => 18
                )

            [2] => Array
                (
                    [store] => 9
                    [price] => 
                )

        )

)

后:

Array
(
    [2016-05-28] => Array
        (
            [0] => Array
                (
                    [store] => 1
                    [price] => 12
                )

            [1] => Array
                (
                    [store] => 7
                    [price] => 18
                )

            [2] => Array
                (
                    [store] => 9
                    [price] => 
                )

            [3] => Array
                (
                    [store] => 8
                    [price] => 
                )

        )

)

答案 4 :(得分:0)

感谢@ trincot评论的帮助,我设法得到了我想要做的事情,使用商店ID作为数组中的键,下面是工作代码。

$setPriceHistoryData = $daoObj->getSetPriceHistoryData($set['id']);
$chartDays = date('Y-m-d', strtotime('-30 days'));
$endDay = date('Y-m-d');
$priceHistoryData = array();

while ($chartDays <= $endDay) {
    for ($i = 0; $i < count($setPriceData["price_history_store_data"]); $i++) {
        $store = $setPriceData["price_history_store_data"][$i]["id"];

        for ($j = 0; $j < count($setPriceHistoryData); $j++) {                    
            if ($store == $setPriceHistoryData[$j]["vph_store"]
                && $chartDays == $setPriceHistoryData[$j]["vph_date"]
                && !isset($priceHistoryData[$chartDays][$store])) {
                $priceHistoryData[$chartDays][$store] =  $setPriceHistoryData[$j]["vph_price"];
            } else {
                if (!isset($priceHistoryData[$chartDays][$store])) {
                    $priceHistoryData[$chartDays][$store] = null;
                }
            }
        }
    }

    // Increment day
    $chartDays = date('Y-m-d', strtotime("+1 day", strtotime($chartDays)));
}

答案 5 :(得分:0)

由于您愿意更改数据结构,因此只需几行简单的代码即可实现另一种非常酷的方法。首先将数据源更改为新的形状,其中商店ID是键,价格是值

$history = [
    '2016-06-15'=>[
        1=>10, 2=>10, //On June 15, store 1 had price 10 
    ],
    '2016-06-16'=>[
        1=>10, 3=>10,
    ],
    '2016-06-17'=>[
        3=>10, 4=>10,
    ],
];

现在你所要做的就是在你的源代码中循环,并在数组上使用+运算符添加任何缺少的存储(它会添加缺少的键)

$required_stores = [1,2,3,4]; // stores you wish to add if missing

//will be [1=>null, 2=>null, 3=>null, 4=>null]
$required_keys = array_combine(
                $required_stores,
                array_fill(0,count($required_stores),null)
    );
//go through each day and add required keys if they're missing
foreach ($history as &$stores):
    $stores += $required_keys
endforeach;

array_combined returns an array使用第一个参数作为键,第二个参数作为值。