So I got two associative arrays containing key-value pairs. They share one key name, and I want to add one array to the other if the "name" values are equal.
So if you have these arrays:
$array1 = [name=>"Foo",
date=>array("2016-06-06", "2016-06-05", "2016-06-04"),
(some other key-value pairs)];
$array2 = [name=>"Foo",
date=>array("2016-06-06", "2016-06-05", "2016-06-04"),
download_count=>array(54,23,15),
(some other key-value pairs)];
the result should be something like this:
$newArray = [name=>"Foo",
date=>array("2016-06-06", "2016-06-05", "2016-06-04"),
(the other key-value pairs from $array1),
app=>array(
name=>"Foo",
date=>array("2016-06-06", "2016-06-05", "2016-06-04"),
download_count=>array(54,23,15),
(the other key-value pairs from $array2))]
Right now I try to loop through both of the array's to see where the names of both array's at index $i,$j are the same, and if they are combine the two.
Here is the code I use for that
foreach($array1 as $foo){
foreach($array2 as $bar){
if($foo["name"] == $bar["name"]){
$foo["app"] = $bar;
}
}
}
alternatively I tried with just regular for loops like this:
for($i = 0; $i < count($array1); $i++){
for($j = 0; $j < count($array2); $i++){
if($array1[$i]["name"] == $array2[$j]["name"]){
$array1[$i]["app"] = $array2[$j];
break;
}
}
}
The result from the first example is just $array1 (unchanged), and the result form the alternative example is an infinite loop.
Could someone help figure out how to get the desirable result?
Edit
Got it working, was just a beginners error in this case both for loops increased $i by one instead of the first loop adding one to $i and the other adding ine to $j
Related
This is my Associative Array:
$vetor = array(
"Name"=> "myName",
"Tel"=> "555-2020",
"Age"=> "60",
"Gender"=> "Male"
);
How I can show only three elements using the loop for?
I tried this:
for($i=0; $i<=2; $i++){
echo $vetor[$i]."<br>";
}
But without success. How I can do this?
You referring to wrong indexes because to reference the first element on your array you have to do something like : $vetor["Name"] instead of $vetor[0]
$i = 0;
foreach($vetor as $key => $value){
if($i == 2){ break; }
echo $value;
$i++;
}
foreach makes more sense for an array like this, but if you want to use for for whatever reason, the problem you'll have is that the array doesn't have sequential numeric indexes that correspond to your loop increment variable. But there are other ways to iterate over the first three elements without knowing what the indexes are.
// this first step may not be necessary depending on what's happened to the the array so far
reset($vetor);
$times = min(3, count($vetor));
for ($i = 0; $i < $times; $i++) {
echo current($vetor).'<br>';
next($vetor);
}
If next moves the internal array pointer beyond the last array element, current($vetor) will return false, so setting $times using min with the number of times you want and the array count will prevent you from looping more times than there are items in the array.
Another way, if you don't care what the keys are, is to use array_values to convert the array keys to numbers.
$vetor = array_values($vetor);
for ($i=0; $i < 3; $i++) {
echo $vetor[$i].'<br>';
}
This question already has answers here:
Combining php arrays
(3 answers)
Closed 7 years ago.
I have two arrays:
$arr1= array("A","B","C");
$arr2= array("1","2","3");
Output i need as:
$arr3= array("A","1","B","2","C","3");
Can anyone help please?
If your first two arrays has the same length, you can use a loop to get the array you want:
<?PHP
$arr1= array("A","B","C");
$arr2= array("1","2","3");
$arr3=[];
for($i = 0; $i < count($arr1); $i++)
array_push($arr3, $arr1[$i], $arr2[$i]);
?>
It will return:
$arr3= array("A","1","B","2","C","3");
Take a look at array_merge()
array_merge ( array $array1 [, array $... ] )
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.
If the input arrays have the same string keys, then the later value
for that key will overwrite the previous one. If, however, the arrays
contain numeric keys, the later value will not overwrite the original
value, but will be appended.
This will work to combine the two arrays together:
$output = $array1 + $array2;
This snippet could solve what you asked, also if arrays are not equal in length.
function array_interpolation($arr1, $arr2) {
$result = array();
$len1 = count($arr1);
$len2 = count($arr2);
$maxlen = max($len1, $len2);
for($i = 0; $i < $maxlen; $i++) {
if($i < $len1) {
array_push($result, $arr1[$i]);
}
if($i < $len2) {
array_push($result, $arr2[$i]);
}
}
return $result;
}
I want to delete a value of a numbered index's array, and then compact the array so the left index is not empty. This is my code but i'd like to know if there is an array method which do that
for ($j = 30; $j < count($a); $j++) {
if ($j+1 < count($a)) {
$a[$j] = $a[$j+1];
}
}
array_pop($a);
So this code remove the value of index 30 of the array and compact the array.
I could use unset(a[30]) but that left me with an array with no index 30. And I can't iterate correctly that array.
You can iterate the array using foreach however to answer the index question:
unset($a[30]);
$a = array_values($a);
You might also use:
array_splice($a, 30, 1);
I have an Array with 8 arrays inside.
It looks like this:
[[num,...],[num,...],[num,...],[num,...],[num,...],[num,...],[num,...],[num,...]]
Each of this inner arrays has as its first element a number. Now I want to receive the element of the outer array with the biggest number as first element.
How do I do that?
Thank you very much.
You can define any sorting algorithm by using PHP's usort()
usort($array, function($a, $b) {
return $a[0] > $b[0];
});
This will sort your array, in place, such that the first element will have the largest number as it's first element.
It's not necessary (and is much more expensive) to sort the entire array. Something like this would work:
// initially, regard the first element as the largest
$element = $array[0];
$greatest = $array[0][0];
$length = count($array);
// compare the first value of each array against $greatest, swapping $element if it's larger
for($i = 1; $i < $length; $i++) { // N.B. start with second element
if($array[$i][0] > $greatest) {
$element = $array[$i];
}
}
// $element is now the element with the biggest first value
Check out usort : http://php.net/manual/en/function.usort.php
You'll have to write your own comparison function.
I'm looking for an efficient algorithm for detecting equal values in an array of integers N size. It must return the indices of the matches.
Alas, I can't think of anything more clever then brute force with two loops.
Any help will be appreciated.
Thanks!
You could intersect the array. This finds all the values of array2 that are in array1
$array1 = array("a" => "green", "b" => "brown", "c" => "blue", "red");
$array2 = array("a" => "green", "yellow", "red");
$result_array = array_intersect_assoc($array1, $array2);
print_r($result_array);
Would return
Array
(
[a] => green
)
It returns an array with all of the keys and values of the matches. Basically you can provide an infinite number of arguments to the array_insert_assoc:
array_intersect_assoc($base_array, $arr1, $arr2 ...);
It will search $base_array for the values that are in all the subsequent arrays. That means that the key and value will be taken from the $base_array
You could also compare the keys by using:
array_intersect_keys($base_array, $arr1, $arr2, $arr3);
These loops are O(N^2). Is N big? If so, can you sort the array O(NlogN), then scan it O(N)? ... or am I missing something?
You can use a set to hold the recent values. For example,
results = empty list
set = empty set
foreach key, val in array:
if val is not in set: add val to set
else: add key to results
return results
Each look up of set is O(1), so this algo will results in O(n) instead of O(n^2) if nested-loop is used.
In case you want to keep track of multi-occurence like this array 1, 2, 3, 3, 2, 1 you can use a hash table with key is the value and value (of the corresponding key in table) is the list of indices. The result for the given array will look lik {1:0, 5; 2: 1, 4; 3: 2, 3}.
results = empty hashtable
for each key, val in array:
if val is not in results:
results[val] = new list()
results[val].append(key)
return results
Perhaps this?
$arr = array_map('unserialize', array_unique(array_map('serialize', $arr)));
From the question: How to remove duplicated 2-dimension array in PHP?
if ($arr !== array_map('unserialize', array_unique(array_map('serialize', $arr))))
{
// found duplicates
}
You don't have to go through all the array again for each element. Only test an element with the subsequent element in the array:
$array = /* huge array */;
$size = count($array);
for($i = 0; $i < $size; $i++)
{
for($j = $i + 1; $j < $size; $j++) // only test with the elements after $i
{
if($array[$i] == $array[$j])
return true; // found a duplicate
}
return false; // found no duplicate
}
That's the most efficient way I can think of. Adapt it to your need as you will.
If one of your arrays is reasonably static (that is you are comparing to the same array several times ) you could invert it.
That is set up another array which is keyed by value and returns the index into the real array.
$invert = array();
foreach ($cmptoarray as $ix => $ival) {
$invert[$ival] = $ix;
}
Then you simply need an if ( isset($invert[$compfrmarray[$i]) ) .... to check the number.
Note: this is only worth doing if you compare against the same array several times!
Just use an associative array mapping a value to its index:
foreach($array1 as $index => $value) {
$aa[$value] = $index;
}
foreach($array2 as $index => $value) {
if(isset($aa[$value])) {
echo 'Duplicate: . Index 1: '.$aa[$value].' Index 2: '.$index.'.';
}
}