I decided to completely ignore the "if it ain't broke don't fix it" rule some of our intranet pages.
I've only been developing in PHP for almost a year and I got a bit cocky, thinking I was better at arrays that I am.
In my code I used to perform a database query, which would return an array with my values.
The array was a single dimension, with each array item, containing 8 different values separated by ||||| as a delimiter.
Then I did a foreach loop, and exploded the array value based on the ||||| delimiter, then parsing the values into separate variables.
Code: Select all
foreach ($dbarray as $key => $arrayvalue) {
// EXPLODE OUR ARRAY
$arrayvalueexp = explode("|||||", $arrayvalue);
$recordid = $arrayvalueexp[0];
$companyname = $arrayvalueexp[1];
$telephonenum = $arrayvalueexp[2];
echo $recordid." ".$companyname." ".$telephonenum;
}I thought I'd try and tidy my code up a bit.
I am under the impression that for this kind of stuff, multidimensional arrays are the way to go - for performance and ease of management.
So now I have my array being sent to me in this format (I've checked this using print_r)...
Code: Select all
$dbarray[0][0] = "recordid";
$dbarray[0][1] = "companyname";
$dbarray[0][2] = "telephonenum";
$dbarray[1][0] = "recordid1";
$dbarray[1][1] = "companyname1";
$dbarray[1][2] = "telephonenum1";
$dbarray[2][0] = "recordid2";
$dbarray[2][1] = "companyname2";
$dbarray[2][2] = "telephonenum2";Code: Select all
foreach ($dbarray as $key => $arrayvalue) {
$recordid = $arrayvalue[0];
$companyname = $arrayvalue[1];
$telephonenum = $arrayvalue[2];
echo $recordid." ".$companyname." ".$telephonenum;
}Because the foreach loop effectively runs 9 times, whereas I only want it to run on the first dimension of the data.
How can I change my loop so that I only iterate though the first dimension, then access the vars from the second dimension directly (without a nested loop) from within my loop?
Is that possible?
Or am I barking up the wrong tree and should continue to just explode my array value as before.
I just thought it was about time I tackled this issue - despite reading many tutorials on the net, I've never felt comfortable with multidimensional arrays.
So an explanation of how to solve this problem would be very much appreciated.
Thanks
Ben