I have two arrays $t1 and $t2. When I print them out I get the following:
t1:
Array ( [0] => Christina Aguilera [1] => Iron Maiden [2] => Bob Marley )
t2:
Array ( [0] => Bob Marley )
I'm trying to get the common elements of the array though the array_intersect function, and I'm using the below line:
$intersection = array_intersect($t1,$t2);
However, for some reason when I print the result $intersection I get get:
Array ( )
Can anybody see what it is going wrong? The code for my function is below but I think the above should be sufficient to work it out.
// For extra information
function findMutualInterests($_uProArray, $_tProArray)
{
$_commonDetails = null;
$_fieldNames = array_keys($_uProArray[0]);
$_uProValues = array_values($_uProArray[0]);
$_tProValues = array_values($_tProArray[0]);
//print_r($_uProValues);
// Iterate over the arrays and find ones in common
for ($i = 0; $i < count($_uProValues); $i++) {
$t1 = explode(',',$_uProValues[$i]);
print_r($t1);
$t2 = explode(',',$_tProValues[$i]);
print_r($t2);
$intersection = array_intersect($t1,$t2);
print_r($intersection);
$_commonDetails[$_fieldNames[$i]] = implode($intersection);
}
return $_commonDetails;
}
EDIT: Just thought I would point out that the output of $t1 and $t2 shown above are the output of a single iteration of the below function. I just chose that one as an example.
Your code works fine, try trimming input strings.
Your code has a huge mistake.
If you have more elements in $_tProValues than in $_uProValues you will not test all possibilities in the $_tProValues array. Then you'll not be able to test all possibilities. What happens here is exactly that, you're not testing all possibilities.
Check the comments above, because this works just fine:
<?php
$a = array (
0 => 'Christina Aguilera',
1 => 'Iron Maiden',
2 => 'Bob Marley'
);
$b = array (
0 => 'Bob Marley'
);
$intersect = array_intersect( $a, $b );
print_r( $intersect );
?>
Output:
Array
(
[2] => Bob Marley
)
**Check the code it is very useful for you ,because this works fine:**
$final_arr = [];
foreach ($a as $a_val) {
foreach ($b as $b_val) {
if(in_array(strtolower($a), array_map('strtolower', $b_val))){
$final_arr[] = $b_val;
}
}
}
Related
I've the following variable that is dinamically created:
$var = "'a'=>'123', 'b'=>'456'";
I use it to populate an array:
$array=array($var);
I can't do $array=array('a'=>'123', 'b'=>'456') because $var is always different.
So it shows me:
Array
(
[0] => 'a'=>'123', 'b'=>'456'
)
This is wrong, 'cause I need to get:
Array
(
[a] => 123
[b] => 456
)
What is wrong on my code?
Thanks in advance.
Ideally you should just leverage PHP's syntax to populate an associative array, something like this:
$array = [];
$array['a'] = '123';
$array['b'] = '456';
However, you could actually write a script which parses your input to generate an associate array:
$var = "'a'=>'123', 'b'=>'456'";
preg_match_all ("/'([^']+)'=>'([^']+)'/", $var, $matches);
$array = [];
for ($i=0; $i < count($matches[0]); $i++) {
$array[$matches[1][$i]] = $matches[2][$i];
}
print_r($array);
This prints:
Array
(
[a] => 123
[b] => 456
)
I have a little problem. Here is the code:
$arr = explode(',', $odluka);
$arr2 = array($arr[0], $arr[1], $arr[2], $arr[3], $arr[4], $arr[5], $arr[6], $arr[7], $arr[8], $arr[9]);
while ($arrk = current($arr2)) {
if ($arrk == '1') {
$ark = key($arr2);
//print_r($ark);
//echo $arr2[$ark];
$arop = explode(',', $utroseno);
$aropk = array($arop[0], $arop[1], $arop[2], $arop[3], $arop[4], $arop[5], $arop[6], $arop[7], $arop[8], $arop[9]);
$array = array($aropk[$ark]);
print_r($array);
}
next($arr2);
}
Output of $array is
Array ( [0] => 1 ) Array ( [0] => 5 ) Array ( [0] => 10 ) Array ( [0] => 4 ) Array ( [0] => 4 ) Array ( [0] => 1 ) Array ( [0] => 1 )
How can I merge this values and sum them. I want sum of 1+5+10+4+4+1+1. Thanks!
declare a variable to store sum
iterate over array
-> add value to sum
Here is a simple example how to deal with your output array:
$data = [
[1], [5], [10], [4]
];
$sum = array_sum(array_map(function($elem) { return $elem[0]; }, $data));
var_dump($sum);
You don't need to assign them to another array and loop..you can just sum everything after explode. You just need one line of code for that:
array_sum(explode(',', $odluka));
Then you'll get the sum of all the numbers
Not need using any array and loop.You are using only "array_sum ()" php building function.Like
<?php
$foo[] = "12";
$foo[] = 10;
$foo[] = "bar";
$foo[] = "summer";
echo array_sum ($foo); //same as echo "22";
?>
For more information Read Php Manual link
Use this function
array_sum ($arr);
I am writing a script to compare the achievements of one player to another in a game. In each of the arrays the id and timestamp will match up on some entries. I have included a sample of one of the start of the 2 separate arrays:
Array
(
[0] => Array
(
[id] => 8213
[timestamp] => 1384420404000
[url] => http://www.wowhead.com/achievement=8213&who=Azramon&when=1384420404000
[name] => Friends In Places Higher Yet
)
[1] => Array
(
[id] => 6460
[timestamp] => 1384156380000
[url] => http://www.wowhead.com/achievement=6460&who=Azramon&when=1384156380000
[name] => Hydrophobia
)
I want to find all of the array items where the id and timestamp match. I have looked into array_intersect but I don't think this is what I am looking for as it will only find items when the entries are identical. Any help much appreciated.
You may use array_intersect_assoc function.
Try something like this:
<?php
$key_match = Array();
//Loop first array
foreach($array as $key => $element){
//Compare to second array
if($element == $array2[$key]){
//Store matching keys
$key_match[] = $key;
}
}
?>
$key_match will be an array with all matching keys.
(I'm at work and havn't had time to test the code)
Hope it helps
EDIT:
Fully working example below:
<?php
$a1["t"] = "123";
$a1["b"] = "124";
$a1["3"] = "125";
$a2["t"] = "123";
$a2["b"] = "124";
$a2["3"] = "115";
$key_match = Array();
//Loop first array
foreach($a1 as $key => $element){
//Compare to second array
if($element == $a2[$key]){
//Store matching keys
$key_match[] = $key;
}
}
var_dump($key_match);
?>
If you want to go on an exploration of array callback functions, take a look at array_uintersect. It's like array_intersect except you specify a function to use for the comparison. This means you can write your own.
Unfortunately, you need to implement a function that returns -1, 0 or 1 based on less than, same as, greater than, so you need more code. But I suspect that it'll be the most efficient way of doing what you're looking for.
function compareArrays( $compareArray1, $compareArray2 ) {
if ( $compareArray1['id'] == $compareArray2['id'] && $compareArray1['timestamp'] == $compareArray2['timestamp'] ) {
return 0;
}
if ( $compareArray1['id'] < $compareArray2['id'] ) {
return -1;
}
if ( $compareArray1['id'] > $compareArray2['id'] ) {
return 1;
}
if ( $compareArray1['timestamp'] < $compareArray2['timestamp'] ) {
return -1;
}
if ( $compareArray1['timestamp'] > $compareArray2['timestamp'] ) {
return 1;
}
}
var_dump( array_uintersect( $array1, $array2, "compareArrays") );
I have 2 arrays that I have made into an Associative Array. I also have combinations of winner positions = ie '1,2', '2,3', '1,3'. What I need to do is replace the position numbers with jersey numbers and put back into the same configuration as the combinations were written. For Example, I've set up my jersey, position, combo, and associative array:
$jersey = array('3','1','5','4');
$position = array('1','2','3','4');
$AssocArr = array_combine($position, $jersey);
$Combo = array('1,2','2,3','1,3');
I've set up a function to get the values from the keys:
function getVals($finishPosMap, $keys) {
foreach($keys as $key) {
$output[] = $finishPosMap[$key];
}
return $output;
}
The part I'm having issue with is putting them back into an array with the values instead of keys. This is what I've done so far:
foreach($Combo as $set=>$pCombo) {
$com = array($set=>(explode(',', $pCombo)));
foreach($com as $set=>$com){
$c = getVals($AssocArr, $com);
print_r($c);
}
}
print_r gives me:
array( [0] => 3 [1] => 1 )
array( [0] => 1 [1] => 5 )
array( [0] => 3 [1] => 5 )
Can anyone help me put it in the format:
array(0 => '3,1', 1 => '1,5', 2 => '3,5');
Thanks in advance for your help, and please let me know if you think there'd be a better way to do this. Thanks!
I think what you're missing is the array_intersect_key(); this should do it:
$jersey = array('3','1','5','4');
$position = array('1','2','3','4');
$AssocArr = array_combine($position, $jersey);
$Combo = array('1,2','2,3','1,3');
foreach ($Combo as &$value) {
$values = explode(',', $value, 2);
$new_values = array_intersect_key($AssocArr, array_flip($values));
$value = join(',', $new_values);
}
print_r($Combo);
It updates the $Combo array in-place and for each value, calculates the intersection with your associate array.
Demo
I have an associative array, however when I add values to it using the below function it seems to overwrite the same keys. Is there a way to have multiple of the same keys with different values? Or is there another form of array that has the same format?
I want to have:
42=>56
42=>86
42=>97
51=>64
51=>52
etc etc
Code:
function array_push_associative(&$arr) {
$args = func_get_args();
foreach ($args as $arg) {
if (is_array($arg)) {
foreach ($arg as $key => $value) {
$arr[$key] = $value;
$ret++;
}
}else{
$arr[$arg] = "";
}
}
return $ret;
}
No, you cannot have multiple of the same key in an associative array.
You could, however, have unique keys each of whose corresponding values are arrays, and those arrays have multiple elements for each key.
So instead of this...
42=>56 42=>86 42=>97 51=>64 51=>52
...you have this:
Array (
42 => Array ( 56, 86, 97 )
51 => Array ( 64, 52 )
)
A key is an extension of a variable. If you overwrite the variable... You overwrite the variable.
No, you cannot have. A workaround I use is to have each key/value pair as a new array with 2 elements:
$test = array(
array(42,56),
array(42,86),
array(42,97),
array(51,64),
array(51,52)
)
For example, you can access the second key (=42) using:
$test[1][0]
and the second value(=86) using:
$test[1][1]
I found this question while researching the exact opposite intended outcome, I have an array of data that has duplicate keys! Here's how I did it (still trying to figure out where in my process things are messing up).
$session = time();
$a = array();
$a[(string)$session] = 0;
$j = json_encode($a,JSON_FORCE_OBJECT);
print_r($a);
/* output:
Array
(
[1510768034] => 0
)
*/
var_dump($a);
/* output:
array(1)
(
[1510768034] => int(0)
)
*/
print_r($j);
/* output:
{"1510768034":0}
*/
$a = (array)json_decode($j);
$session = #array_pop(array_keys($a));
$a[(string)$session] = 10;
$j = json_encode($a,JSON_FORCE_OBJECT);
print_r($a);
/* output:
Array
(
[1510768034] => 0
[1510768034] => 10
)
*/
var_dump($a);
/* output:
array(2)
(
'1510768034' => int(0)
[1510768034] => int(10)
)
*/
print_r($j);
/* output:
{"1510768034":0,"1510768034":10}
*/
Yup....that just happened.
PHP 7.1
Edit: It's similar in PHP 7.2.10, except json_encode no longer entertains duplicate keys, encoded strings are correct. The array, however, can have matching string and integer keys.
i had the same need too create an array with the same keys, (just to keep performance by using two loops rather than 4 loops).
by using this : [$increment."-".$domain_id] => $article_id;
my list of articles in each domain looks like this after a print_r() :
$AllSa = Array
(
[1-5] => 143
[2-5] => 176
[3-5] => 992
[4-2] => 60
[5-2] => 41
[6-2] => 1002
[4-45] => 5
[5-45] => 18
[6-45] => 20
)
And then by looping through this table to associate article by domain :
$AssocSAPerDomain = array();
$TempDomain = "";
$TempDomain_first = 0;
foreach($tree_array as $id_domain => $id_sa){
if( !$TempDomain && $TempDomain_first == 0 ){ $TempDomain = substr(strrchr($id_domain, "-"), 1); $TempDomain_first = 1; }
$currentDomain = substr(strrchr($id_domain, "-"), 1);
//if($TempDomain == $currentDomain)
$AssocSAPerDomain[$currentDomain][] = $id_sa;
$TempDomain = substr(strrchr($id_domain, "-"), 1);
}
you get this
$assoc= Array
(
[5] => 143
=> 176
=> 992
[2] => 60
=> 41
=> 1002
[45]=> 5
=> 18
=> 20
)
it is not possible technically. But I created a fun way to do it. Be alert, this answer is just for the fun, the ultimate goal is to get the output anyway.
So here is the answer. You first need to convert to the whole array to the string. Then the rest of the things is just string replace and a little code.
<?php
$ary="array('a'=>123,'a'=>161,'a'=>195)";
$str = str_replace("array(", "", $ary);
$str = str_replace(")", "", $str);
$arr = explode(",",$str);
foreach($arr as $element){
$element = str_replace("=>", "", $element);
$element = str_replace("'", "", $element);
echo $element.'<br>';
}
?>
Here is the output