i have multidimension array
$a = "5,add|4,edit|6,add|6,edit|19,add|19,delete|19,view";
then i explode $a
$array_a = explode("|", $a);
//loop
for($i=0;$i<=count($arr_a)-1;$i++){
arr_b = explode(",", $arr_a[$i]);
foreach($arr_b as $id => $access){
echo $id." have access ".$access;
}
}
//result
0 have access 5
1 have access add
0 have access 4
1 have access edit
0 have access 6
1 have access add
0 have access 6
1 have access edit
0 have access 19
1 have access add
0 have access 19
1 have access delete
0 have access 19
1 have access view
//-end result
the problem is :
how i can make the result like this
5 have access add
4 have access edit
6 have access add,edit
19 have access add,delete,view
I think Regex would be a better solution in this case, in case you haven't considered using it.
Sample (Tested):
$a = "5,add|4,edit|6,add|6,edit|19,add|19,delete|19,view";
$result = array();
// match each pair in the input
if (preg_match_all('/(\\d+)\\,(.*?)(\\||$)/m', $a, $matches)){
foreach( $matches[1] as $match_index => $match ){
$result[$match][] = $matches[2][$match_index];
}
}
// loop through the results and print in desired format
foreach( $result as $entry_index => $entry ){
echo "$entry_index have access " . implode( ',', $entry ) . "\n";
}
output:
5 have access add
4 have access edit
6 have access add,edit
19 have access add,delete,view
Using regex simplifies the code and also makes it somewhat easier to change the format of the input that is supported.
The $result array ended up with a hash map using your numeric ids as the keys and arrays of permissions (add, delete, etc) as the value for each key.
Try this one (tested):
// intial data
$strAccess = "5,add|4,edit|6,add|6,edit|19,add|19,delete|19,view";
// build access array
$arrayAccess = array();
$tmpList = explode('|', $strAccess);
foreach($tmpList as $access)
{
list($idUser, $right) = explode(',', $access);
if (!isset($arrayAccess[$idUser]))
$arrayAccess[$idUser] = array();
$arrayAccess[$idUser][] = $right;
}
// print it out
foreach($arrayAccess as $idUser => $accessList)
echo $idUser." has access ".implode(",", $accessList)."\n";
You can use counter something like
$count5=0;
foreach($arr_b as $id => $access){
if($access=='5'){
$count5++;
}
echo $id." have access ".$count5;
}
$a = "5,add|4,edit|6,add|6,edit|19,add|19,delete|19,view";
$array_a = explode("|". $a);
//loop
$aRights = array();
for($i=0;$i<=count($arr_a)-1;$i++){ $arr_b = explode(",", $arr_a[$i]);
foreach($arr_b as $id => $access){
$aRights[$id][] = $access;
}
}
foreach( $aRights as $id=>$rightsList){
echo $id." have access ";
$i=1;
foreach($rightsList as $r){
echo $r;
if($i != count($rightsList)) echo ",";
$i++;
}
}
What about something like hashmapping:
$tobegenerated = array();
$a = explode(yourdelimiter,yourstring);
foreach ($a as $cur)
{
$b = explode(delimiter,$cur);
$tobegenerated[$cur[0]] = $cur[1];
}
//Print hashmap $tobegenerated
This should work, remember that in php arrays are also hash maps
Edit 1:
Arrays in PHP are hash maps. A hash map can be interpreted as an array where keys can be anything and value can be anything too. In this case, you would like to use a hash map because you need to bind values that are "outside" the range of the array (even if they are ints). So a hash map is exactly what you want, allowing to specify anything as a key.
How a hash map work is something that you can search on google or on wikipedia. How arrays work in php can be found here
Related
I have this code:
public function get_names($number){
$names = array(
'None',
'Anton',
'bertha',
'Cesa',
'Dori',
'Egon',
'Frank',
'Gollum',
'Hans',
'Kane',
'Linus',
'Moose',
'Nandor',
'Oliver',
'Paul',
'Reese');
$bin = strrev(decbin($number));
$len = strlen($bin);
$output = array();
foreach(str_split($bin) as $key=>$char)
{
if ($key == sizeof($names)){
break;
}
if($char == 1)
{
array_push($output,$names[$key]);
}
}
return $output;
}
When I now call the function with number - let's say - 32256 I would get an array with "Kane, Linus, Moose, Nandor, Oliver, Paul".
Can anyone tell me what I would have to do when I want to give a certain names array and wanna get the number as a result where the certain bits are included? So exactly the other way around.
I found that code somewhere which works fine. But I need it vice versa.
Thanks in advance!
Andreas
EDIT: I want to know the decimal number when I e.g. have an array with "Anton, bertha,Cesa". I want to store those in a database instead of storing arrays with names each time. And when I need the names I just take the decimal number from database and use my function to get my name arrays.
If you just take the position in your $names array as being the bit position, you raise 2 to this position to give it the correct bit position and keep a running total of the items found...
$input = ["Cesa", "Gollum", "Hans"];
$output = 0;
foreach ( $input as $digit ) {
$output += pow(2,array_search($digit, $names ));
}
echo $output; // 392
with
$input = ["Kane", "Linus", "Moose", "Nandor", "Oliver", "Paul"];
gives
32256
Or as Barmar points out in his comment, you can save the lookup by inverting the names array using array_flip() which will mean that looking up each key will give the position in the array...
$output = 0;
$names = array_flip($names);
foreach ( $input as $digit ) {
$output += pow(2,$names[$digit]);
}
echo $output;
I have the following array
$array = array(
1=>"a",
2=>"b",
4=>"c",
8=>"d",
16=>"e"
);
Then I have the following number $var = 12; This number comes from the sum of keys from the array above. (obviously $var changes).
How can I find the keys that actually create $var.
In the example:
12 = array key 4 + array key 8
Hope I was clear...
Binary numbers. Magic XD
$array = array(1=>"a",2=>"b",4=>"c",8=>"d",16=>"e");
$results = array();
$num = 12;
foreach($array as $i=>$v) {
if( $num & $i) $results[$i] = $v;
}
// in this case, you get $results = array(4=>"c",8=>"d");
Is there a fast way of doing something like this Compare two arrays with the same value but with a different order in PHP?
I have arrays with potentially same data but in different order and I just need to see whether they are identical.
OK, turns out I get back an object and not an array, I guess...
object(Doctrine\ORM\PersistentCollection)#560 (9) etc.
hmm... Would the easiest way perhaps to iterate over the contents of the collection in order to create my own array and then compare like you all suggested?
Just adding code for my final solution
//Find out if container receives mediasync
$toSync = array();
foreach($c->getVideosToSync() as $v) {
$toSync[] = $v->getId();
}
$inSync = array();
foreach($c->getVideosInSync() as $v) {
$inSync[] = $v->getId();
}
$noDiff = array_diff($toSync, $inSync);
$sameLength = count($toSync) === count($inSync);
if( empty($noDiff) && $sameLength ) {
$containerHelper[$c->getId()]['syncing'] = false;
}
else {
$containerHelper[$c->getId()]['syncing'] = true;
}
I solved it the following way:
<?php
$arrayOld=array(
'1'=>'32',
'2'=>'34',
'3'=>'36',
'4'=>'38',
'5'=>'40',
'6'=>'42',
'7'=>'44',
);
$arrayNew=array(
'2'=>'32',
'1'=>'34',
'3'=>'36',
'4'=>'38',
'5'=>'46',
'6'=>'42',
'7'=>'44',
);
/**
* Here we check if there is any difference in keys or values in two arrays
* array_intersect_assoc - returns values that are same in both arrays checking values as well as keys
* array_diff returns the difference between the arrayNew values and those same values in both arrays, returned by array_intersect_assoc
*/
$result = array_diff($arrayNew,array_intersect_assoc($arrayOld, $arrayNew));
print_r($result);
//result is:
Array (
[2] => 32,
[1] => 34,
[5] => 46,
)
/** We can see, that the indexes are different for values 32 and 34
* And the value for index 5 has also changed from 40 to 46
*/
Just get them in a uniform order using sort() & then diff with them with array_diff().
# Set the test data.
$array1 = array(1,2,3,4,9,10,11);
$array2 = array(3,4,2,6,7);
# Copy the arrays into new arrays for sorting/testing.
$array1_sort = $array1;
$array2_sort = $array2;
# Sort the arrays.
sort($array1_sort);
sort($array2_sort);
# Diff the sorted arrays.
$array_diff = array_diff($array1_sort, $array2_sort);
# Check if the arrays are the same length or not.
$length_diff = (count($array1) - count($array2));
$DIFFERENT_LENGTH = ($length_diff != 0) ? true : false;
# Check if the arrays are different.
$ARE_THEY_DIFFERENT = ($array_diff > 1) ? true : false;
if ($DIFFERENT_LENGTH) {
echo 'The are different in length: ' . $length_diff;
}
else {
echo 'They have the same length.';
}
echo '<br />';
if ($ARE_THEY_DIFFERENT) {
echo 'They are different: ' . implode(', ', $array_diff);
}
else {
echo 'They are not different.';
}
echo '<br />';
//Returns 10 question from questions table
$result = mysqli_query($con,"SELECT question FROM questions ORDER BY rand() LIMIT 10' ");
while($row = mysqli_fetch_row($result))
{
$que[]=$row[0];
}
Now I need to store this whole set of $que[] in a session variable. (i.e 10 questions)
Something like this
$_SESSION['question'] = $que[];
$my_array[] = $_SESSION['question'];
so that $my_array[0] returns first question, $my_array[1] returns second questions and like that.
(Thanx for the help in advance)
Assign
$_SESSION['question'] = $que;
print_r($_SESSION['question'][0]); will give you first question.
You are almost correct, you only need the [] when adding to the array.
$_SESSION['question'] = $que;
Make sure that you have a session going first, placing this at the top of your script will start a session if one doesn't already exist:
if( !isset( $_SESSION ) ) {
session_start();
}
To pull it back up:
$array = $_SESSION['question']; //Assigns session var to $array
print_r($array); //Prints array - Cannot use echo with arrays
Final Addition
To iterate over the array, you can typically use for, or foreach. For statements really only work well when your array keys are incremental (0, 1, 2, 3, etc) without any gaps.
for( $x = 0, $max = count($array); $x < $max; ++$x ) {
echo $array[$x];
}
foreach( $array as &$value ) {
echo $value;
}
Both have been written in mind for performance. Very important to know that when using a reference (&$value, notice the &) that if you edit the reference, the original value changes. When you do not use by reference, it creates a copy of the value. So for example:
//Sample Array
$array = array( '0' => 5, '1' => 10 );
//By Reference
foreach( $array as &$value ) {
$value += 2; //Add 2 to each value
echo $value; //Echos 7 and 12, respectively
}
print_r( $array ); //Now equals array( '0' => 7, '1' => 12 )
//Normal Method
foreach( $array as $value ) {
$value += 2; //Add 2 to each value
echo $value; //Echos 7 and 12, respectively
}
print_r( $array ); //Still equals array( '0' => 5, '1' => 10 )
References are faster, but not if you are planing on modifying the values while keeping the original array intact.
use
session_start();
$_SESSION['question'] = $que;
&que = array(an array of your 10m question s);
when your want to call it on another page to get a line up of your questions, use
while (list($key, $value) = each($_SESSION)) {
#Echo the questions using $key
echo "Here is a list of your questions";
echo "<br/>";
while (list($key2, $value2) = each($_SESSION)) {
#$value2 show's name for the indicated ID
#$key2 refers to the ID
echo "<br/>";
echo "Question: ".$value2." ";
echo "<br/>";
}
echo "<br/>";
}
OR you can also use
print_r;
Hope my title explains it ok! Here's more detail:
I'm creating an array which stores keys & their values. Eg.
test1 = hello
test2 = world
test3 = foo
What is the cleanest way of working out what to call the next key? Let's say I will know the first part is 'test', but I don't know what the highest value number is. Obviously in this case I want it to be called 'test4'.
In the example below I want the next key to be 'test46', as it is the next highest value:
test6 = blah
test45 = boo
test23 = far
This sounds like you should be using an array with numerical indexes instead.
You could however use some code like this...
$arr = array('test6', 'test45', 'test23');
$max = 0;
foreach($arr as $value) {
$number = filter_var($value, FILTER_SANITIZE_NUMBER_INT);
$max = max($max, $number);
}
$newKey = 'test' . ++$max; // string(6) "test46"
CodePad.
Implementation of #alex answer without using a loop:
$arr = array('test6', 'test45', 'test23');
$max = max(filter_var_array($arr, FILTER_SANITIZE_NUMBER_INT));
$newKey = 'test' . ++$max; // string(6) "test46"
CodePad
This data structure would be better stored as an array.
$test = array();
$test[] = 'hello';
$test[] = 'world';
$test[] = 'foo';
You then don't need to know the highest number to add a new item, just use the empty brackets syntax (shown above) to add an item to the end of the array.
You then have access to a wealth of array functions that PHP gives you to work with your data: http://php.net/manual/en/ref.array.php
When you want to get item 43 from the array, use:
echo $test[42];
Arrays are counted from 0 rather than 1, so item 43 will have an index of 42.
What are you using that for? If numbering the array is a must-have, just use a simple numerical indexed array instead, and simply prepend the key with "test" if you need it to show up as "test1":
<?php
$array = array(
6 => 'blah',
45 => 'boo',
23 => 'bar'
);
$array[] = 'new';
echo $array[46] . "\n"; // this is 'new'
foreach( $array as $key => $value ) {
echo "test$key = $value<br />\n"; // test6 = blah
}