我意識到有關於多維數組和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中使用它。
任何意見,如何得到這個工作或優化它,將不勝感激。
P.S.正如我上面提到的,我知道這個問題之前已經被問到 - 儘管我無法讓他們的解決方案爲我工作。如果解決方案是重複的(如對其他人沒有幫助),我將刪除此問題。感謝您的幫助,非常感謝!
什麼是你的PHP版本?在PHP> = 5.5上,你可以使用['array_column'](http://php.net/manual/en/function.array-column.php):'in_array($ a ['filename'],array_column($ items [$ i-1] ['files'],'name'))' – fusion3k
感謝提示@ fusion3k。我將閱讀關於該功能的文檔,並嘗試一下。 – turnfire