[英]iterate through 3 dimensional array php
I have created a 3 dimensional array (Fig 1) from a MySQL query (fig 2). 我已经从MySQL查询(图2)创建了3维数组(图1)。 The top level is [Expense_ID] and the next level up is [Participant_ID]. 顶层是[Expense_ID],下一层是[Participant_ID]。 There can be multiple Participant_ID's for each Expense_ID. 每个Expense_ID可以有多个Participant_ID。
Qu 1) Although the data is all repeated at the bottom level of the array, please could someone tell me how I can iterate through this array as it is (at each level) to echo out the structure as per the original data (if I can echo it out, then I can perform the calculations I need to do). Qu 1)尽管数据都是在数组的最底层重复的,但有人可以告诉我如何遍历此数组(在每个级别)以根据原始数据回显该结构(如果我可以回显它,然后我就可以执行所需的计算)。 ie in the echo statement, [Expense_ID] would be taken from the top level of the array, [Participant_ID] would be taken from level 2 and the remaining 3 fields would be taken from the bottom level. 即在echo语句中,[Expense_ID]将从数组的顶层获取,[Participant_ID]将从级别2获取,其余3个字段将从底层获取。
Qu 2) I don't know if this is the best array structure. Qu 2)我不知道这是否是最好的数组结构。 The code I used to get to this array is shown in fig 3. How could I change this so that level one shows as [0] => 86 and level 2 is [0] => 130, 1 => 135 This might be easier to work with. 我用于获取此数组的代码在图3中示出如何可以改变这使得一个水平显示为[0] => 86和电平2 [0] => 130, 1 => 135,这可能是更容易使用。
Qu 2a) How then would I iterate through the array if it is in this format? Qu 2a)如果数组是这种格式,那么我将如何遍历数组?
Any help would be much appreciated. 任何帮助将非常感激。
Array
(
[86] => Array
(
[130] => Array
(
[Expense_ID] => 86
[Expense_Description] => Item1
[Total_Amount] => 3000.00
[Expense_Payer_ID] => 134
[Participant_ID] => 130
)
[135] => Array
(
[Expense_ID] => 86
[Expense_Description] => Item1
etc.
$result = array();
while ($row = mysql_fetch_array($Exps)){
$Exp_ID = $row['Expense_ID'];
$Participant_ID = $row['Participant_ID'];
$result[$Exp_ID][$Participant_ID] = array(
'User_ID' => $row['User_ID'],
'Expense_ID' => $row['Expense_ID'],
etc.
);
}
I'm not sure I understand what you are asking but I think a simple foreach loop will do the trick. 我不确定我是否理解您的要求,但我认为一个简单的foreach循环就能解决问题。
foreach ($result as $id => $participants) {
// here your Expense_ID == $id
foreach ($participants as $pid => $value) {
// here Participant_ID == $pid
//
// Total_Amount == $value['Total_Amount']
// Expense_Description == $value['Expense_Description']
// ....
}
}
Hope this can help. 希望这会有所帮助。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.