【问题标题】:Multidimensional array loop with array search带数组搜索的多维数组循环
【发布时间】:2016-04-11 13:59:46
【问题描述】:

我意识到有很多关于多维数组和 foreach 循环的问题,我花了几个小时阅读它们并试图让我自己的循环工作——但没有成功。如果解决方案重复,我将删除我的问题(如果愿意,可以链接到另一个问题)。

现在,挑战:

  • 使用返回的 MYSQL 结果数组。结果来自关联数组中的多个连接表。现在我需要将其转换为我需要的多维数组。
  • 我已经完成了大部分工作,但我的问题是循环遍历并将新项目添加到数组中的正确位置。

这里有一些代码:

//example of how array is setup in the way I want, this part works.
foreach($results as $i => $a):

    //some other code is here, see below.

    $items[$i] = [
        "id" => $a['id'],
        "itemid" => $a['itemid'],
        "name" => $a['name'],
        "def" => $a['def'],
        "class" => $a['class'],
        "timeline" => $a['timeline'],
        "files" => [
            [0] => [
                "id" => $a['fileid'],
                "name" => $a['filename'],
                "path" => $a['filepath'],
                "type" => $a['filetype']
            ]
        ],
        "tags" => [
            [0] => [
                "id" => $a['tagid'],
                "name" => $a['tagname']
            ]
        ]
    ];
endforeach;

然后我尝试了多种循环方式,以便仅在项目“id”与上一个相同时添加到“标签”或“文件”。这是我编辑器中的当前代码,无法正常工作:

//inside foreach loop, before above code
if($items[$i-1]['id'] == $a['id']):
    //it is the same item, works to here.
    if(in_array($a['filename'], $items[$i-1], FALSE)):
        //add to files array for last item
        $items[$i-1]['files'][] = [
            "id" => $a['fileid'],
            "name" => $a['filename'],
            "path" => $a['filepath'],
            "type" => $a['filetype']
        ];
    elseif(in_array($a['tagname'], $items[$i-1], FALSE)):
        //add to tags array for last item
        $items[$i-1]['tags'][] = [
            "id" => $a['tagid'],
            "name" => $a['tagname']
        ];
    endif;
else:// else it does the code above

如您所见,我最近的尝试是使用 in_array,我现在意识到它不适用于多维数组。我的问题是我不知道如何确定它是同一项目的新文件还是新标签。

最终,我想要一个包含多个“文件”和“标签”的“项目”数组。之后我要去json_encode和JS一起使用。

任何关于如何使它工作或优化它的建议,将不胜感激。

附:正如我上面提到的,我知道以前有人问过这个问题——尽管我无法让他们的解决方案为我工作。如果解决方案是重复的,我将删除这个问题(例如,它对其他人并没有真正的帮助)。感谢您的帮助,非常感谢!

【问题讨论】:

  • 你的 PHP 版本是多少?在 PHP >= 5.5 上,您可以使用 array_column : in_array( $a['filename'], array_column( $items[$i-1]['files'], 'name' ) )
  • 感谢@fusion3k 的提示。我会阅读有关该功能的文档并试一试。

标签: php mysql arrays multidimensional-array


【解决方案1】:

不要使用“自动递增”数组索引,因为它们很容易弄乱。使用您的数据库 ID,因为它已经存在:

//example of how array is setup in the way I want, this part works.
foreach($results as $i => $a):
$items[$a['id']] = [ // THIS CHANGED.
    "id" => $a['id'],
    "itemid" => $a['itemid'],
    ...

现在,有了任何进一步的结果,您可以轻松检查 id 是否已经在您的数组中:

if (isset($items[$a['id']])) {
  // We had this id before, just add files/tags to it.
  // Check first, if files subarray exists, if not: create it.
  if (!isset($items[$a['id']]['files'])) {
    $items[$a['id']]['files'] = array();
  }
  $items[$a['id']]['files'][] = array(...); // add the new file.
  // Repeat for tags.
}

如果您的结果可能多次返回同一个文件的 id,您可以使用搜索功能检查文件名是否已经存在:

$filename = $a['filename'];
if (!searchFilename($filename, $items[$a['id']]['files']) {
  // Filename is not in there, yet.
  // Add file info.
}

function searchFilename($id, $array) {
  foreach ($array as $key => $val) {
    if ($val['filename'] === $id) {
       return true;
    }
  }
  return false;
}

同样适用于标签。

最后,如果您不想要$items 的索引ID,只需调用:

$items = array_values($items);

【讨论】:

  • 我想我现在明白我哪里出错了——使用索引。如果有超过 1 个附加文件/标签,则它正在查看数组中的错误索引。感谢您的解释和时间!我很确定您的解决方案对我有用。一旦我在我的代码中得到它,我会确认/标记解决方案:P(P.S.我应该删除这个问题,还是留下它?这个缺陷在我的逻辑中=P随意留下意见作为cmets。)
  • 没错,因为$i 会递增,而不管$a['id'] 之前是否被处理过。
  • 我做了一些改动,但您的解决方案正是我所需要的。我完全改变了我的数组的设置方式,使用文件/标签 ID 作为它们的索引。再次感谢保罗,你真棒!
猜你喜欢
  • 2016-05-22
  • 2016-05-03
  • 2011-07-05
  • 1970-01-01
  • 1970-01-01
  • 2016-05-26
  • 2011-11-29
  • 2011-06-26
相关资源
最近更新 更多