Reputation: 65
I have a shopping cart ($_SESSION[cart_array]). I want to populate a select/option list with just the unique GroupName field from that array.
My approach was to 1) create a new array with just the GroupName field, and then 2)create a third array that has just the unique values using array_unique().
I recognize that this may not be the most efficient manner, and welcome suggestions.
However, before I even reached that point, I had a more basic problem. I seem to only be assigning the first letter of the variable.
$GroupNames = array();
foreach($_SESSION[cart_array] as $h) {
echo $h['GroupName']."<br>";
$GroupNames[] = $h['GroupName'];
}
foreach ($GroupNames as $entry) {
echo $entry['GroupName'] . "<br>";
}
print_r($GroupNames);
The output of the code above is: Crystal Farm
Java Garden Batiks
Java Garden Batiks
Java Garden Batiks
Crystal Farm - Precuts
Crystal Farm - Precuts
C
J
J
J
C
C
Array ( [0] => Crystal Farm [1] => Java Garden Batiks [2] => Java Garden Batiks [3] => Java Garden Batiks [4] => Crystal Farm - Precuts [5] => Crystal Farm - Precuts )
My research makes it seem that I'm not declaring $GroupName as an array, but it looks to me like I am. So, I'm lost. Thanks in advance.
Upvotes: 1
Views: 45
Reputation: 1890
$GroupNames[] = $h['GroupName'];
Is literally building an array of group names eg:
$GroupNames = array(
"group1",
"group2"
)
But then you do this
foreach ($GroupNames as $entry) {
// This bit is looking for a key which does not exist.
echo $entry['GroupName'] . "<br>";
//Instead try
echo $entry . "<br>";
}
OR, maybe you actually do want a multidimensional array. In which cause when building it here:
foreach($_SESSION[cart_array] as $h) {
$GroupNames[] = $h['GroupName']; //current
// You want the following
$GroupNames[] = array("GroupName" => $h['GroupName']);
}
However, with the current example I think I'd go with option 1.
Upvotes: 1