How can I create an associative array using for each? - php

I am selecting checkboxes and want to save in an associative array with current page number $_GET['page_no'] as it's index, but only 1 value goes in, why no other?
$pageno = $_GET['page_no']; //Say page no is 1
$_SESSION['selected_vals'] = array();
foreach($_POST['record_num'] as $throw_rec_nums) {
$_SESSION['selected_vals'][$pageno] = $throw_rec_nums;
}
What I expect
$_SESSOION['selected_val'] (
[1] => 24
[1] => 46
[1] => 56
)
But I only get 24 even if 3 checkboxes are selected
Note: $_GET['page_no'] is returned as array

$pageno is not incrementing. In order for more than one value to be added to the array, it needs to be incremented while in the loop.
A solution would be something like:
$_SESSION['selected_vals'][$pageno][] = $throw_rec_nums;
That way all record numbers would be saved to the array at the page number specified.

Only 1 value goes in because your are replacing $_SESSION['selected_vals'][$pageno] value on each loop of foreach.
try create a counter to index it
it is a option
$_SESSION['selected_vals'] = array();
$_SESSION['selected_vals'][$pageno] = array();
foreach($_POST['record_num'] as $throw_rec_nums) {
$_SESSION['selected_vals'][$pageno][] = $throw_rec_nums;
}

You cannot use an array as array index. You will have to iterate over $pageno too, for example with next():
$array[current($pageno)] = ...;
next($pageno);
Note that this will only work if you make sure rt that $pageno actually IS an array and contains enough elements.

Related

add into multidimension array in PHP

I am trying to create/fill two multidimension arrays within a loop.
$internal_array = array();
$external_array = array();
Within a loop, I am trying fill them randomnly, so for example if, for every iteration, my variable is "internal", I'll fill internal_array otherwise external_array.
This array has three cells as shown below.
I am not sure how would I insert into my array, as an example, this is what I am trying:-
$internal_array = array("mystring1", "mynumber1", "order1");
$external_array = array("mystring4", "mynumber4", "order4");
This seems to not work for somereason.
I am hoping that by the end of loop, I'd have a multidimensional array like:-
internal_array = [0] ("mystring1", "mynumber1", "order1")
[1] ("mystring2", "mynumber2", "order2")
[2] ("mystring3", "mynumber3", "order3")
external_array = [0] ("mystring4", "mynumber4", "order4")
[1] ("mystring5", "mynumber5", "order5")
[2] ("mystring6", "mynumber6", "order6")
Any idea please?
Thanks.
In the loop with every occurrence you are re-populating the same variable over and over again $internal_array = [some_value], so it will contain the last values populated only, using $internal_array[] = [some_value] will add every item in the loop as a subsequent array member
for($i=0; $i<count; $i++){
if ($category == "internal") {
$internal_array[] = array("mystring1", "mynumber1", "order1");
}
elseif ($category == "external") {
$external_array[] = array("mystring4", "mynumber4", "order4");
}
}
You could also add them all in one shot like this:
array_push(
$internal_array,
array("mystring1", "mynumber1", "order1"),
array("mystring2", "mynumber2", "order2"),
array("mystring3", "mynumber3", "order3")
);
See array_push()

Incrementing an array's value is causing warnings in the log

I am trying to create an array that holds the count of each course we offer based on location and then instructor. Here is sample code
$courseCnt = array();
foreach($courseList as $course){
$courseCnt[$course['location']][$course['instructor']] += 1
}
This code creates the array properly and displays well but I get a bunch of warnings like:
Unidentified index "Orlando" for locations, Unidentified index "John
Smith" for instructor
I have found that if I just make it = 1 instead of += 1 the warnings go away but of course this makes every course for location/instructor 1 which is not good.
My next though was checking if it exists, if it doesn't, make it 1 and if it does += 1. Here is an example
if(isset($courseCnt[$course['location']][$course['instructor']]){
$courseCnt[$course['location']][$course['instructor']] += 1
}else{
$courseCnt[$course['location']][$course['instructor']] = 1
}
This results in the fatal error:
Cannot use string offset as an array
$course array structure is just a 2 dimensional array pulled from sql
Sample:
courseID location instructor
1 Orlando John Smith
2 Detroit Bill Murray
You are not checking if the location exists before checking for the instructor in your first line of the new version of the code. You need to check if it exists and create it in your $courseCnt array if it doesn't (as an empty array). After that, you can check for the instructor:
// Initialise the empty array
$courseCnt = array();
// Create location if not in array
if( ! isset($courseCnt[$course['location']])) {
$courseCnt[$course['location']] = array();
}
// Either increment the instructor or create with initial value of 1
if ( isset($courseCnt[$course['location']][$courseCnt[$course['instructor']]]) ) {
$courseCnt[$course['location']][$courseCnt[$course['instructor']]] += 1;
}
else
{
$courseCnt[$course['location']][$courseCnt[$course['instructor']]] = 1;
}
You've got a lot of square brackets going on in there, so you might find it easier to read if you use PHP's array_key_exists (documentation) instead of isset:
// Initialise the empty array
$courseCnt = array();
// Create location if not in array
if( ! array_key_exists($course['location'], $courseCnt)) {
$courseCnt[$course['location']] = array();
}
// Either increment the instructor or create with initial value of 1
if ( array_key_exists($course['instructor'], $courseCnt[$course['location']]) ) {
$courseCnt[$course['location']][$courseCnt[$course['instructor']]] += 1;
}
else
{
$courseCnt[$course['location']][$courseCnt[$course['instructor']]] = 1;
}

increment value inside an array of arrays (if key is non-existent, set it to 1)

Question has been updated to clarify
For simple arrays, I find it convenient to use $arr[$key]++ to either populate a new element or increment an existing element. For example, counting the number of fruits, $arr['apple']++ will create the array element $arr('apple'=>1) the first time "apple" is encountered. Subsequent iterations will merely increment the value for "apple". There is no need to add code to check to see if the key "apple" already exists.
I am populating an array of arrays, and want to achieve a similar "one-liner" as in the example above in an element of the nested array.
$stats is the array. Each element in $stats is another array with 2 keys ("name" and "count")
I want to be able to push an array into $stats - if the key already exists, merely increment the "count" value. If it doesn't exist, create a new element array and set the count to 1. And doing this in one line, just like the example above for a simple array.
In code, this would look something like (but does not work):
$stats[$key] = array('name'=>$name,'count'=>++);
or
$stats[$key] = array('name'=>$name,++);
Looking for ideas on how to achieve this without the need to check if the element already exists.
Background:
I am cycling through an array of objects, looking at the "data" element in each one. Here is a snip from the array:
[1] => stdClass Object
(
[to] => stdClass Object
(
[data] => Array
(
[0] => stdClass Object
(
[name] => foobar
[id] => 1234
)
)
)
I would like to count the occurrences of "id" and correlate it to "name". ("id" and "name" are unique combinations - ex. name="foobar" will always have an id=1234)
i.e.
id name count
1234 foobar 55
6789 raboof 99
I'm using an array of arrays at the moment, $stats, to capture the information (I am def. open to other implementations. I looked into array_unique but my original data is deep inside arrays & objects).
The first time I encounter "id" (ex. 1234), I'll create a new array in $stats, and set the count to 1. For subsequent hits (ex: id=1234), I just want to increment count.
For one dimensional arrays, $arr[$obj->id]++ works fine, but I can't figure out how to push/increment for array of arrays. How can I push/increment in one line for multi-dimensional arrays?
Thanks in advance.
$stats = array();
foreach ($dataArray as $element) {
$obj = $element->to->data[0];
// this next line does not meet my needs, it's just to demonstrate the structure of the array
$stats[$obj->id] = array('name'=>$obj->name,'count'=>1);
// this next line obviously does not work, it's what I need to get working
$stats[$obj->id] = array('name'=>$obj->name,'count'=>++);
}
Try checking to see if your array has that value populated, if it's populated then build on that value, otherwise set a default value.
$stats = array();
foreach ($dataArray as $element) {
$obj = $element->to->data[0];
if (!isset($stats[$obj->id])) { // conditionally create array
$stats[$obj->id] = array('name'=>$obj->name,'count'=> 0);
}
$stats[$obj->id]['count']++; // increment count
}
$obj = $element->to->data is again an array. If I understand your question correctly, you would want to loop through $element->to->data as well. So your code now becomes:
$stats = array();
foreach ($dataArray as $element) {
$toArray = $element->to->data[0];
foreach($toArray as $toElement) {
// check if the key was already created or not
if(isset($stats[$toElement->id])) {
$stats[$toElement->id]['count']++;
}
else {
$stats[$toElement->id] = array('name'=>$toArray->name,'count'=>1);
}
}
}
Update:
Considering performance benchmarks, isset() is lot more faster than array_key_exists (but it returns false even if the value is null! In that case consider using isset() || array_key exists() together.
Reference: http://php.net/manual/en/function.array-key-exists.php#107786

How to get value of an array inside an array

Example:
foreach ($AllowAttributes as $attribute) {
$medida_cart = $attribute['options'];
print_r($medida_cart);
}
Displays on the screen Array ( [22] => 5.40 x 2.10 )
I want this value 5.40 x 2.10 without having to use the index
$medida_cart = $attribute['options'][22];
The index 22 will be changed forever, and always will have only one value, example:
Array ([random] => data I need)
Use current() or reset():
$medida_cart = reset($attribute['options']);
$medida_cart = array_values($attribute['options'])[0];
This will make the associative array into a sequential array and get the first and only value.
array_values() DOCUMENTATION

How to split an Array into usable data, so it can be counted and manipulated

I have this query:
SELECT carID FROM reservations WHERE startDate < '".$sqlretdate."' AND endDate > '".$sqlcoldate."' OR startDate = '".$sqlcoldate."' OR endDate = '".$sqlretdate."'"
Using a loop:
while($presentid = mysql_fetch_array($checkreservations)) {
This returns an array of data, so for example:
echo "<---space-->";
print_r($presentid['carID']);
Would display:
<---space-->11<---space-->10<---space-->2<---space-->8<---space-->9<---space-->7
This is a list of ids, I need to do something with each of them.
I can explode it:
print_r(explode(" ", $presentid['carID']));
And this would make it print like this:
Array ( [0] => 11 ) Array ( [0] => 10 ) Array ( [0] => 2 ) Array ( [0] => 8 ) Array ( [0] => 9 ) Array ( [0] => 7 )
How do I totally split each id and store it into a variable, so I can use them to do something else?
In this case each ID is unique to a car, and has a model name associated to it, so I want to use the id to find out which model name is related to it, count the number of that model name in the database, and then check to see how many of the returned ids related to that model, and therefore how many there is left. I hope that makes sense.
In your while loop, $presentid represents each row in the result set. $presentid['carID'] is not an array! It's one carID value. You do not need to use explode here at all.
while($presentid = mysql_fetch_array($checkreservations)) {
// This *is* each car ID! Do with it what you want.
$carID = $presentid['carID'];
}
$ids = array();
$count = 0;
while($presentid = mysql_fetch_array($checkreservations)) {
$ids['car_' . $count++] = $presentid['carID'];
}
extract($ids);
This will give you independent variables:
$car_0 = 11;
$car_1 = 12;
$car_2 = 2;
..etc
You can't store it into a basic variable without overwriting it, unless you want to reserve very many variables, It's best to go through the loop, store the values into an array, then you can walk trough the array once the while loop is over, unless you can just do something with them right away.
"How do I totally split each id and store it into a variable"
while($presentid = mysql_fetch_array($checkreservations))
{
$carId = $presentid['carID'];
$array[] = array('id' => $carId );
}
So you can parse through the array once It's over.

Categories