Forum Moderators: coopster

Message Too Old, No Replies

Accessing Values of Multi-dimensional Arrays

         

SeanF

2:35 pm on Aug 14, 2022 (gmt 0)

5+ Year Member Top Contributors Of The Month



So, in order to minimize MySQL calls (and improve performance), I have decided to have the database call write values to a Multi-dimensional SESSION arrays. Then I call call the values directly from the session rather than multiple, (sometimes duplicate MySQL queries. I am new to multi-dimensional arrays and this is probably a real newbie question...

I have successfully written the session array and can call if back across pages, looping through the following for each company:

$co_array = array(
"co_id"=>"$co_id",
"sales_id"=>"$sales_id",
"company_name"=>"$company_name",
"password"=>"$password",
"email"=>"$email",
"opt_out"=>"$opt_out",
"contact_first_name"=>"$contact_first_name",
"contact_last_name"=>"$contact_last_name",
"contact_first_name"=>"$contact_first_name",
"contact_first_name"=>"$contact_first_name"
);
array_push($_SESSION['company_list'],$co_array); // Items added to multi-dimensional array


I can retrieve the array on subsequent pages using:
foreach ($_SESSION['company_list'] as $key => $value) {
echo "Key: $key: <br/>";
foreach ($value as $sub_key => $sub_val) {
echo "$sub_key, $sub_val. <br/>";
}
}

This does, in fact output the company list correctly.

However, I am having trouble accessing variable name/value pairs such that I can can use the variable in formulas or conditionals. For example: If a 'key' name is "company_name", and its value is "ABC Company, Inc." how do I set (or create) a variable named "compay_name" and have its value set to the value from the array? Logically, within the "foreach ($value as $sub_key => $sub_val) {" loop I would assign php variable/value pairs but I am not sure how to do that.

SeanF

5:04 pm on Aug 14, 2022 (gmt 0)

5+ Year Member Top Contributors Of The Month



Ah... Ithink I have it through some trial and error. The following code seems to do what I want:
foreach ($_SESSION['company_list'] as $key => $value) {
echo "Key: $key<br/>";
// $value is an array of company information
// print_r($value);
foreach ($value as $sub_key => $sub_val) {
echo "Sub Key: $sub_key Value: $sub_val<br/>";
$$sub_key = $sub_val;
}
echo "Co Name $company_name, Pwd: $password<br/>";
}


The key was the "$$" to take the value of "$sub_key" and turn it into a variable name. Let me know if this is not good practice