I have an array split in half, but now i want to use the values in the array.
The array is split like this
$teams = array_chunk($lista, count($lista)/2);
Output
Array ( [0] => Array ( [0] => 4 [1] => 3 ) [1] => Array ( [0] => 4 [1] => 4 ) )
the numbers represent user id's.
How can i use these numbers?
Let's say that i want to select all id's in the first array (The idea is for these two arrays to act like teams) and then assign these values to a team column in my database.
Let me explain a bit more
I want the id's in the array to be assigned to a team.
In array one the team will be, uhm. Blue! and in the other array the team will be red.
I will be using these randomised arrays to update my database table which contains a column called "team".
Basically my question is how i can use these arrays to assign the specific id's in each array to a team. example, Can i select everything in array one and update all those values to team blue?
For this question i'm sorry because i really don't know what i should include to make this question answerable, it might already be! but i'm not sure, so i if i have missed something just comment and i will clarify.
Update
This is what my database table looks like
https://gyazo.com/ed3c681575b26f31b77246436b43439a
As you can see, i have a column called "team", i want to update this to something depending on what team the user got selected into using the array splitter.
Everyone in Array one will have this updated to "team blue", and team red for array2.
You could use a For Loop to construct a query that does this for you.
An array inside of an array is called a Multidimensional Array.
You can access the elements of an array inside an array by just simply indexing twice:
$array = [ [1,2], [3,4] ];
echo $array[0][0]; // echo's 1
So you could loop over the first array for each team and loop into the second array to get each user id:
$array = [ [1,2], [3,4] ];
foreach($array as $team_id => $player_ids){
foreach($player_ids as $player_id){
echo "Player $player_id is in team $team_id";
}
}
This example uses a Foreach Loop.
In this for loop you can construct a query that updates the rows for the players in the database.
If you are new to arrays in PHP I suggest you read this article: http://php.net/manual/en/language.types.array.php
Related
I have an array of arrays as following:
$a = array(
1 => array("sport", "geo"),
2 => array("sport", "geo", "history"),
3 => array("geo", "history"),
4 => array("golf", "sport"),
...
);
From that I need to get keys, in such a way so that values are unique.
So from that I would need to get something like:
$b = array( 1, 3, 4 );
$a[2] would be cut out, since it has the same values as $a[1], but since $a[2] is not there, $a[3] is fine.
If some values get completely cut out, that's fine. I will have 30+ keys, from which I need to get 10, which have unique values.
Key is a question ID, and values are tags.
I want to get 10 questions, which are different from each other (so that I don't get 10 questions about Sport).
I tried array_unique(), but that just returns this:
Array (
[1] => Array (
[0] => sport
[1] => geo
)
)
which doesn't seem to help much.
Can you guys point me towards something that could help me?
I guess I could try to list all possible categories, make that array unique, sort it by random. I would need to preserve Keys, but Keys are unique...
you can use array_diff() to detect unique tags
Returns an array containing all the entries from array1 that are not present in any of the other arrays.
Then use array_merge() to store unique value to our $tags variable
Merges the elements of one or more arrays together so that the values of one are appended to the end of the previous one. It returns the resulting array.
<?php
$a = array(
1 => array("sport", "geo"),
2 => array("sport", "geo", "history"),
3 => array("geo", "history"),
4 => array("golf", "sport")
);
$tags = [];
foreach($a as $tag){
$tags = array_merge($tags, array_diff( $tag, $tags));
}
print_r($tags);
Output :
Array
(
[0] => sport
[1] => geo
[2] => history
[3] => golf
)
Just iterate through the initial array of questions, every time save the value (array of tags) to another temporary array with checking if actual tags already exists in temporary array - if not add the question to temporary array, if exists go next. Do it until you have 10 questions in your temporary array, if you finish the question array without already having 10 questions - repeat the iteration but this time add other questions even if the tags are repeating - until you have 10.
I am quite not able to get the logic for my requirement.
Lets consider I have an array
Array
(
[0] => 1
[1] => 1
[2] => 2
[3] => 1
[4] => 3
[5] => 3
)
I would like to split the below array on the basis if the array element matches its previous element.
i.e in the above example value at [1] matches the value at [0]. Hence put it into the same array as [0]. Now check if the value at [2] matches the value at [1] if it matches put it into the same array, if not put it into a different array. The process continues.
Below is an example of the desired outpout.
Array
(
[0] => 1
[1] => 1
)
Array
(
[0] => 2
)
Array
(
[0] => 1
)
Array
(
[0] => 3
[1] => 3
)
Thanks for your help in advance.
Justin
you can obtain that result in a loop checking on previous element. the output can be an array of arrays! (or anything you would prefer.. do your thing here)
$array1 = array(1, 1, 2, 1, 3, 3);
$output_array=array();
$previous_value="";
$output_array_index=0;
foreach ($array1 as $value) {
if($value != $previous_value){
$output_array_index+=1;
}
$output_array[$output_array_index][]=$value;
$previous_value=$value;
}
print_r($output_array);
so, let me know if you need more pointers! array logic is fun, and php will let you do alot, out of the box. though this specific need is not covered, have a look when you have a minute # the manual, it'll save you time in the future, guarantee http://php.net/manual/en/ref.array.php
This question is a bit confusing but doesn't sound too difficult to implement if I'm understanding it correctly. All you need to do is have a temporary array (or array list) that checks user input. If that user input happens to be the same as the previous input (you can keep a counter variable and check to see if ArrayList.get(counter) == ArrayList.get(counter-1)). Keep adding things to this temporary arrayList and once you have a number that is different, just iterate through the arraylist and add it to a new array.
Another question you have to consider is how you are going to store all these arrays. For that you may want to create an ArrayList containing Arrays. That way after you find user input that is different from the previous input you can just use the toArray method provided with the ArrayList class and add it to the ArrayList containing all of your separate Arrays!
Hope this helps!
I am reading a GEDCOM-formatted family tree flat file, and producing an array from the data for staging into table. If I encounter the values CONC <some value>, then, instead of adding an element, I need to append <some value> to the value of the last element that was just inserted (regardless of dimension depth).
I tried with current(...) etc but does this work for a multidimensional associative array?
please consider following element in an array:
[#N163#] => Array ( [INDI] => Array ( [TEXT] => Some data of this person) )
if the next line reads "1 CONC including his profession"
instead of adding a line as such
[#N163#] => Array (
[INDI] => Array ( [TEXT] => Some data of this person)
[INDI] => Array ( [CONC] => including his profession) )
I would like the array to look as follows:
[#N163#] => Array (
[INDI] => Array ( [TEXT] => Some data of this person including his profession) )
What I have researched thus far:
end($theArray)
to set pointer to last inserted element followed by $theArray[key($theArray)] = .... to update this element.
But I did not get this method to work for multidimensional arrays and/or it became really messy.
And:
merging two arrays using e.g. += notation,
but this only seems to overwrite a new element, not affect the last one, if keys are same
And:
examples with foreach calls, which does not help in my case.
Hope somebody can shed some light... many thanks!
When you adding $array[#N163#][INDI][TEXT] = 'smtng'; you can save position
$pos = &$array[#N163#][INDI][TEXT];
And if you need concatenate, write
$pos .= "concate line";
I'm iterating over an array of courses, which all contain category IDs in the form of strings. I'm trying ro group them all by category using a matrix, but I'm having trouble doing that.
Here's an example of what I want:
$courses_by_code = [[2/11]=>[course1],[course2]], [[3/12]=>[course3], [course4]]
So my questions are:
How do I add an element that has a key that's already in the matrix to the array that corresponds to that key?
How do I create a new line in the matrix in case I find a new key?
I am not sure I understood 100%, but from what I understood you should do something like:
$keyThatMightExist // '2/11' for example
if(isset($courses_by_code[$keyThatMightExist])) {
$courses_by_code[$keyThatMightExist][] = $newCourseToAdd;
} else {
$courses_by_code[$keyThatMightExist] = array($newCourseToAdd);
}
Let's start with PHP's Arrays documentation:
An array in PHP is actually an ordered map. A map is a type that associates values to keys.
Something that will be invaluable to you when working with arrays is the print_r function. var_dump is also useful. You will be able to see array structure as its stored in PHP. Here's some useful things to know with arrays.
Let's answer some questions now:
How do I add an element that has a key that's already in the matrix to the array that corresponds to that key? How do I create a new line in the matrix in case I find a new key?
$courses = []; // initialize
$courses['2/11'][] = 'course1';
$courses['2/11'][] = 'course2';
$courses['3/12'][] = 'course3';
$courses['3/12'][] = 'course4';
The empty [] you see indicates that I'm adding more elements to the key 2/11. If I wanted I could also name those keys, but I'm not going to do that. Using print_r (described above) I will now print the array out in a human-readable format. Note that with print_r you generally want to surround the output with <pre> tags, as such:
echo "<pre>";
print_r($courses);
echo "</pre>";
And here is my output:
Array
(
[2/11] => Array
(
[0] => course1
[1] => course2
)
[3/12] => Array
(
[0] => course3
[1] => course4
)
)
Here is how I can access these elements:
echo $courses['2/11'][1]; // this is course2
echo "<br>";
print_r($courses['3/12']); // this is the entire '3/12' array
Result:
course2
Array
(
[0] => course3
[1] => course4
)
I'm getting strange results when trying to check a $_GET variable against a whitelist array. The variable is in the array but in_array is not finding it. I'll descibe what's happening as best I can.
The $_GET vars are set from option/select choices, three altogether. Only one of the options is giving me a problem. To run a SELECT query, there have to be at least two options chosen. Any combination of the other two options works as expected.
To get the option/select lists I have a SELECT query retrieving a record subset.
From that recordset I use a foreach loop to get the various values to populate the select tags. So the select values are populated by values from the db table. The whitelist arrays are copied from the db.
I check any $_GET vars against the whitelist arrays. The option in question can be a comma-delimited string (eg. 'Italian,Pizza' or 'American, Barbeque, Sandwiches').
To get the select value list for this option I use implode to create a comma-delimited list of each category, then use explode to create an array, then use array_unique to get an array with single instances of each category. When echoing this array everything is right (it populates the select choices correctly).
implode outputs:
Italian,Pizza,Italian,Pizza,Italian,Pizza,Italian,Italian,Sandwiches,Italian,Pizza,Italian
explode outputs:
Array
(
[0] => Italian
[1] => Pizza
[2] => Italian
[3] => Pizza
[4] => Italian
[5] => Pizza
[6] => Italian
[7] => Italian
[8] => Sandwiches
[9] => Italian
[10] => Pizza
[11] => Italian
)
array_unique outputs:
Array
(
[0] => Italian
[1] => Pizza
[8] => Sandwiches
)
So, the URL can be like:
../search.php?var_src=Sandwiches&city_src=Cityname
To sanitize the $_GET vars:
if((isset($_GET['var_src'])) && in_array($_GET['var_src'], $var_array)) {
$var_sort = $_GET['var_src'];
}
Again, $var_array is an array copied from the db table.
This is where the code stops because the $_GET var is not being found in the array.
If I change one of the db records to just one category value (eg. 'Sandwiches') and select that option in the list, then the results are as expected. However, if the record has more than one category value (each of which is in the whitelist array) like 'Pizza,Sandwiches', then neither of them work.
The kicker is that if I include the category value 'Italian', whether alone or with other values in the db record, and select for this value, then it works. I have no idea why.
So the code works if that particular value ('Italian') is selected whether or not others are included as a comma-delimited string for the record, and does not work with other values where there are more than one associated with the record.
I confirmed that the offending value is in the URL and so should work with the code above (in_array($_GET['var_src'], $var_array)).
Also, I don't know why changing the db record would have an effect because the sanitizing against the whitelist happens before selecting records based on the passed values. As far as I can tell, in_array is just not finding legitimate values in the array.
Hope I haven't made this confusing. Thanks for any help.
Not sure if this will help you, try to change it like in this example:
$opt = array( 'Italian,Pizza' , 'American, Barbeque, Sandwiches');
$opts = implode(',',$opt);
$opta = explode(',',$opts);
foreach ($opta as $key=>$value) {
$opta[$key]=trim($value);
}
$opta = array_flip($opta);
var_export($opta);
//now test it simply with isset:
$val = trim($_GET['var_src']);
echo isset($opta[$val])? 'yes':'no';