fjm 348
Contributor
For some reason, I have always had a hard time understanding arrays as they pertain to php and databases. I understand associative arrays just fine but when there are multidimensiona l arrays, I kinda don't.
I have gone over a few different examples but they were limited. I was able to find one piece of code that I would like to disect and ask questions about so I can gain a better understanding. - $characters = array
-
(
-
array ( name=>"name 1"
-
, occupation=>"developer"
-
, age=>30
-
, specialty=>"Java"
-
),
-
array
-
(
-
name=>"name 2"
-
, occupation=>"Programmer"
-
, age=>24
-
, specialty=>"C++"
-
),
-
array
-
(
-
name=>"name 3"
-
, occupation=>"designer"
-
, age=>63
-
, specialty=>"Javascript"
-
)
-
);
-
-
foreach ($characters as $val)
-
{
-
foreach ($val as $key=>$final_val)
-
{
-
print "$key: $final_val<br>";
-
}
-
print "<br>";
-
}
In this code, the way I am reading this is that there are 3 "rows"??? or blocks of data. Each one of these rows or blocks has several other rows inside of it. I don't have a problem with the arrays per se but more the foreach loop. If I am incorrect about these 3 arrays being rows, please feel free to correct me.
On the foreach, can someone please tell me exactly how and why it is set up the way it is? Specifically, I don't understand why the coder didn't use a key/value pair. He only uses a value, then inside the loop he uses $key=>$final_va l. What I need to understand is why and when to refer to or use the key value pair and when not to. I have also seen code written inside the foreach loop like so: $key['something'] = $val;
What is that? What exactly does it do? If any one can help me to understand these, I would be forever grateful. I have pulled my hair out for the last time on drawing my data out of an array.
Thanks.
110 7025 Dormilich 8,658
Recognized Expert Moderator Expert
firstly, the posted code should give you quite a bunch of error notices (the keys are set as constants, which I doubt are intended)
if you're familiar with Maths, imagine arrays as matrices where you can access each element with the appropriate index (aka key) values (like $array[$i][$j][$k]). the sample would correspond to a 3x4 matrix. @fjm
the reason for not using a key/value pair in the first loop is, that the keys are not needed by the program/coder (they are numeric values). in the first foreach he loops through the topmost array getting an array as value ($val) (gettype($val) would give you "array") then he loops over that value/this array and prints the keys ($key) and values ($final_val) of this sub-array.
foreach can be used in 2 ways, so you can use the syntax you really need: - // values only
-
foreach ($array as $value)
-
-
//keys and values
-
foreach ($array as $key => $value)
@fjm
it depends on what you want to do, if you don't need the keys you omit them. @fjm
looks strange, I need to see the whole code (part) to explain.
Ciary 247
Recognized Expert New Member @Dormilich
shouldn't that be something like this?
or for an associative array:
in this case, it's used to write to the array in a foreach loop to change its values. next is a multidimentiona l example based on your array. -
$i = 0;
-
foreach($array as $key => $val){
-
$val[0] = "changedname " + $i;
-
$i ++;
-
$array[$key] = $val;
-
}
this code changes the first value on each row to "changednam e " and the row number. to do this you need a key but mostly you wont use it. mostly, you need it when you want to write to the array.
the code as you wrote it cant be right. it states that your $key is an array. or it could be a foreign library i dont know about.
fjm 348
Contributor @Dormilich
Hey Dormilich, thanks for the help. Actually, I ran the code and I don't have any errors or notices and my server is set for E_ALL. @Dormilich
I'm thinking in terms of tables here. Are you saying that your sample would correspond to a table with 1 row and 4 cells? That's what I am seeing. @Dormilich
Since I have posted, I have been looking for that code sample that you didn't seem to understand as well as playing with MD arrays. BTW: Ciary was exactly correct on the code he posted. Please see his example for what I was trying to convey.
In almost everything I do, I will always have my own key. I don't need php to generate the numeric key for me. So, that being the case, would a foreach loop be written any differently from the code that I posted to get my key? @Dormilich
What I understand from your example is that the first foreach you wrote would be good for an assoc array and the second would be for a MD array. Yes?
fjm 348
Contributor @Ciary
Hi Ciary. That's cool! Thanks for the explanation.
Here is what has been happening that has been making me pull my hair out for the past 7 months with regard to arrays. I have a class that gets my results from my database. The method uses mysql_fetch_arr ay and returns the values. Well, along with my key/value pairs, would be an identical, duplicate row of data with the array integer and I could never seem to figure out how to omit the int values. As it turned out, the mysql_fetch_arr ay() in my method used "MYSQL_BOTH " and was the culprit. I changed it to MYSQL_ASSOC and I have been golden ever since. I still want to learn more about arrays though because I have reached a point of understanding where I see that arrays are really helpful in transporting my data in bulk and I can work with it and do whatever I want with it.
Dormilich 8,658
Recognized Expert Moderator Expert @fjm
well, I got the expected 12 notices… @fjm
for a two-dimensional array you can think in terms of tables. but it would be a 3(4) row / 4(3) column table (depending upon where you set the precedence). @fjm
No, the first is if you're only interested in the values. the type of the keys doesn't matter at all.
Dormilich 8,658
Recognized Expert Moderator Expert @fjm
as described in the manual. if you run into such problems, it is always a good idea to read all of the manual entry (even the comments). this solves most of these problems
Ciary 247
Recognized Expert New Member
you're welcome :)
to answer the other question:
a matrix looks like a table with rows and columns. actually thats how arrays work 2. but you also have more dimensions as 2. good example:
$_SESSION is a standard array provided by php. you can put 3 dimentional array in it. in that way, you have a 4D array(there isn't a way to visualize this though).
i hope this isnt making it 2 difficult.
if you already have the key wihout the foreach. you dont need the foreach
example: i want to change the element on row 4 column 8:
note that an array starts at 0 so thats why i lowered my indexes by 1
for the different ways of foreach:
use the one with the key to write and the one without the key to read unless you need the key for something else.
i hope i havent complicated things :)
EDIT: srr for the double post Dormilich. seems like we were posting at the same time
fjm 348
Contributor @Dormilich
Well, let's just say that I'm hard headed and sometimes hate to read. Honestly though, I would not have known about that if someone would not have pointed it out to me.
I really had no idea why I was getting duplicated rows. Now that I have read the manual on the fetch_array function, I feel more comfortable now and can finally concentrate on understanding arrays more. I could never figure out if it was me writing a bad loop or if something else was going on or both.
fjm 348
Contributor @Dormilich
From my ini file: error_reporting = E_ALL & ~E_NOTICE | E_STRICT
I just ran the code again and got nothing. Completely clean. I'm on version 5x @Dormilich
OK so if I understand.. An array over 2D doesn't look like a table? Sometimes I need to visualize something to understand it. I'm also not that familier with maths. I did manage to find a matrix and it resembled a table, kind of.
Sign in to post your reply or Sign up for a free account.
Similar topics |
by: OutsiderJustice |
last post by:
Hi All,
I can not find any information if PHP support multi-thread (Posix
thread) or not at all, can someone give out some information? Is it
supported? If yes, where's the info? If no, is it possible to make
doing multi-thread stuff?
Thanks.
YF
|
by: ajikoe |
last post by:
Hello,
Is anyone has experiance in running python code to run multi thread
parallel in multi processor. Is it possible ?
Can python manage which cpu shoud do every thread?
Sincerely Yours,
Pujo
|
by: Frank Jona |
last post by:
Intellisense with C# and a multi-file assembly is not
working. With VB.NET it is working.
Is there a fix availible?
We're using VisualStudio 2003
Regards
Frank
|
by: cody |
last post by:
What are multi file assemblies good for?
What are the advantages of using multiple assemblies (A.DLL+B.DLL) vs. a
single multi file assembly (A.DLL+A.NETMODULE)?
|
by: Joe |
last post by:
I have 2 multi-list boxes, 1 displays course categories based on a
table called CATEGORIES. This table has 2 fields CATEGORY_ID,
CATEGORY_NAME
The other multi-list box displays courses based on a table called
COURSES. This table has 2 fields CATEGORY_ID, COURSE_NAME.
The CATEGORY_ID is a FK in COURSES and a PK in CATEGORIES.
I want to populate the course list box based on any category(s)
| |
by: dkelly925 |
last post by:
Is there a way to add an If Statement to the following code so if data
in a field equals "x" it will launch one report and if it equals "y" it
would open another report. Anyone know how to modify this?
Private Sub cmdPreview_Click()
On Error GoTo Err_Handler
'Purpose: Open the report filtered to the items selected in the
list box.
'Author: Allen J Browne, 2004. http://allenbrowne.com
Dim varItem As Variant 'Selected items
|
by: Kaz Kylheku |
last post by:
I've been reading the recent cross-posted flamewar, and read Guido's
article where he posits that embedding multi-line lambdas in
expressions is an unsolvable puzzle.
So for the last 15 minutes I applied myself to this problem and come up
with this off-the-wall proposal for you people. Perhaps this idea has
been proposed before, I don't know.
The solutions I have seen all assume that the lambda must be completely
inlined within the...
|
by: =?Utf-8?B?R2Vvcmdl?= |
last post by:
Hello everyone,
Wide character and multi-byte character are two popular encoding schemes on
Windows. And wide character is using unicode encoding scheme. But each time I
feel confused when talking with another team -- codepage -- at the same time.
I am more confused when I saw sometimes we need codepage parameter for wide
character conversion, and sometimes we do not need for conversion. Here are
two examples,
|
by: Sabri.Pllana |
last post by:
We apologize if you receive multiple copies of this call for papers.
***********************************************************************
2008 International Workshop on Multi-Core Computing Systems
(MuCoCoS'08)
Barcelona, Spain, March 4 - 7, 2008; in conjunction with CISIS'08.
<http://www.par.univie.ac.at/~pllana/mucocos08>
***********************************************************************
Context
|
by: mknoll217 |
last post by:
I am recieving this error from my code:
The multi-part identifier "PAR.UniqueID" could not be bound.
The multi-part identifier "Salary.UniqueID" could not be bound.
The multi-part identifier "PAR.UniqueID" could not be bound.
The multi-part identifier "PAR.PAR_Status" could not be bound.
The multi-part identifier "Salary.New_Salary" could not be bound.
The multi-part identifier "Salary.UniqueID" could not be bound.
The multi-part...
|
by: Hystou |
last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it.
First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
| |
by: Oralloy |
last post by:
Hello folks,
I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>".
The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed.
This is as boiled down as I can make it.
Here is my compilation command:
g++-12 -std=c++20 -Wnarrowing bit_field.cpp
Here is the code in...
|
by: jinu1996 |
last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth.
The Art of Business Website Design
Your website is...
|
by: tracyyun |
last post by:
Dear forum friends,
With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
|
by: conductexam |
last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one.
At the time of converting from word file to html my equations which are in the word document file was convert into image.
Globals.ThisAddIn.Application.ActiveDocument.Select();...
|
by: TSSRALBI |
last post by:
Hello
I'm a network technician in training and I need your help.
I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs.
The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols.
I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
|
by: adsilva |
last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
| |
by: 6302768590 |
last post by:
Hai team
i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
|
by: muto222 |
last post by:
How can i add a mobile payment intergratation into php mysql website.
| |