搜索嵌套的多维数组

时间:2016-07-15 08:01:29

标签: php arrays multidimensional-array

我有一个填充数组的函数:

foreach ($request->get('ids') as $id) {
    $pdfArray['other']++; // Yes this is initialized
    $pdfArray['rows'][$i]['id'] = $schedule->getId();
    $pdfArray['rows'][$i]['date'] = $schedule->getStart()->format('d.m.Y');
    $pdfArray['rows'][$i]['dateSort'] = $schedule->getStart()->format('Y-m-d H:i');
    $pdfArray['rows'][$i]['from'] = $schedule->getStart()->format('H:i');
    $pdfArray['rows'][$i]['to'] = $schedule->getEnd()->format('H:i');
    $pdfArray['rows'][$i]['desc'] = $schedule->getDescription();
}

我想做什么

在每个循环中,我想检查数组(到目前为止)是否已经有desc条目等于当前$schedule->getDescription()date$schedule->getStart()->format('d.m.Y')相同(实际上更多,但让我们保持简单)

我尝试了什么

public function recursive_array_search($needle,$haystack) {
    foreach($haystack as $key=>$value) {
        $current_key=$key;
        if($needle===$value OR (is_array($value) && $this->recursive_array_search($needle,$value) !== false)) {
            return $current_key;
        }
    }
    return false;
}

Source

我这样使用它:

if ($this->recursive_array_search($schedule->getDescription(), $pdfArray['rows']) &&
    $this->recursive_array_search($schedule->getStart()->format('d.m.Y'), $pdfArray['rows'])){
       $pdfArray['ma'][$schedule->getId()]++;
}

但当truestart中的任何一个在当前数组中是SOMEWHERE时,这是desc

如何查看是否找到descstart是否在$i级别?

编辑,例如

假设我有10 $id个循环。在2次循环之后,$pdfArray看起来像这样:

Array
(
[other] => 2
[rows] => Array
    (
        [0] => Array
            (
                [id] => 1
                [date] => 13.07.2016
                [dateSort] => 2016-07-13 08:00
                [from] => 08:00
                [to] => 09:00
                [desc] => TEST
            )

        [1] => Array
            (
                [id] => 2
                [date] => 12.07.2016
                [dateSort] => 2016-07-12 08:00
                [from] => 08:00
                [to] => 09:00
                [desc] => TEST
            )

    )

下一次迭代有以下内容:

$schedule->getStart()->format('d.m.Y') => 12.07.2016

$schedule->getDescription() => TEST

所以我想得到组合已存在于数组中的信息。

BUT

$schedule->getStart()->format('d.m.Y') => 12.07.2016

$schedule->getDescription() => TEST2

检查存在后,

不应该返回true。

3 个答案:

答案 0 :(得分:1)

在验证功能中尝试此操作

library(shiny)

runApp(shinyApp(

  ui = fluidPage(
    title = "minimal-working-example",
    fluidRow(
      column(3, inputPanel(
        selectInput("field", "Field", choices = names(mtcars)),
        numericInput("value", "Value", 0),
        actionButton("submit", "Submit")
      )),

      column(9,
        DT::dataTableOutput("table")
      )
    )
  ),

  server = function(input, output) {

    v <- reactiveValues(mtcars=mtcars)
    previousSelection <- NULL
    previousPage <- NULL

    observeEvent(input$submit, {
      previousSelection <<- input$table_rows_selected
      previousPage <<- input$table_rows_current[1] - 1

      v$mtcars[input$field] <- input$value
    })

    output$table <- DT::renderDataTable({
      DT::datatable(
        v$mtcars,
        selection = list(mode = "single", target = "row", selected = previousSelection),
        options = list(pageLength = 5, displayStart = previousPage))
    })
  }
))

并像这样调用 public function array_search($needle1, $needle2 ,$haystack) { foreach($haystack as $singleArray){ if (in_array($needle1, $singleArray) && in_array($needle2, $singleArray)) return true; else continue; } return false; }

recursive_array_search

答案 1 :(得分:1)

测试&#34;重复&#34;你可以使用这个功能:

function testPresence($pdfArray, $desc, $date) {
    foreach ($pdfArray["rows"] as $row) {
        if ($row["desc"] == $desc && $row["date"] == $date) return true;
    }
}

使用示例:

echo testPresence($pdfArray, "TEST2", "12.07.2016") ? "Found" : "Not found"; // Not found
echo testPresence($pdfArray, "TEST", "12.07.2016") ? "Found" : "Not found"; // Found

在原始循环中,您可以按如下方式使用它:

foreach ($request->get('ids') as $id) {
    if (testPresence($pdfArray, $schedule->getDescription(), 
                                $schedule->getStart()->format('d.m.Y')) {
        // We have a duplicate. Maybe skip this entry?:
        continue;
    }

    $pdfArray['other']++;
    $pdfArray['rows'][$i]['id'] = $schedule->getId();
    $pdfArray['rows'][$i]['date'] = $schedule->getStart()->format('d.m.Y');
    $pdfArray['rows'][$i]['dateSort'] = $schedule->getStart()->format('Y-m-d H:i');
    $pdfArray['rows'][$i]['from'] = $schedule->getStart()->format('H:i');
    $pdfArray['rows'][$i]['to'] = $schedule->getEnd()->format('H:i');
    $pdfArray['rows'][$i]['desc'] = $schedule->getDescription();
}

答案 2 :(得分:1)

功能版本:

/** 
 * Find matches for $item into pdfArray.
 * Returns an index array, possibly empty if no matches.
 * @param $item      item to find
 * @param $rows      rows where to search
 */
function findPdfArrayMatches(array $item, array $rows) {
    return array_keys(
  array_filter(
    $rows,
    function ($entry) use ($item) {

      // These are the matching criteria. More than one row may match.

      return $entry['desc'] == $item['desc']
          && $entry['date'] == $item['date']
      ;

    }
  )
);
}

你可以在循环中这样做:

$item = [
    'id'        => $schedule->getId(),
    'date'      => $schedule->getStart()->format('d.m.Y'),
    'dateSort'  => $schedule->getStart()->format('Y-m-d H:i'),
    'from'      => $schedule->getStart()->format('H:i'),
    'to'        => $schedule->getEnd()->format('H:i'),
    'desc'      => $schedule->getDescription(),
];

$matches = findPdfArrayMatches($item, $pdfArray['rows']);

if (!empty($matches)) {
    ...do something with the matches:
    foreach ($matches as $match) {
        $pdfArray['rows'][$match]['Duplicate'] = true;
    }
}
// Add new item
$pdfArray['rows'][$i] = $item;