0

I have created a 3 dimensional array (Fig 1) from a MySQL query (fig 2). The top level is [Expense_ID] and the next level up is [Participant_ID]. There can be multiple Participant_ID's for each Expense_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). i.e. 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.

Qu 2) I don't know if this is the best array structure. 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.

Qu 2a) How then would I iterate through the array if it is in this format?

Any help would be much appreciated.

Fig 1: Array Structure

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. 

Fig 2

Fig 2: Data from MySQL query

Fig 3

 $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. ); } 

1 Answer 1

2

I'm not sure I understand what you are asking but I think a simple foreach loop will do the trick.

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.

Sign up to request clarification or add additional context in comments.

2 Comments

Thanks @ggMomo. I was getting confused with referencing each layer and this has helped hugely. Duplicate values was not an issue however. :)
Happy I could help! (I'll edit my post to remove the duplicate values part)

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.