I want to compare keys from one array against values from another array, and when a match is made to store the value from the first array (whose key matched the value in the second one).
With my code, it always echoes out 4. How can I modify it so that it echoes out 1 2 3 4?
The code:
$first = array('location', 'genre', 'studio', 'Lord_Of_the_Rings');
$second = array(
'location' => 1,
'genre' => 2,
'studio' => 3,
'Lord_Of_the_Rings' => 4
);
while ($el = current($second)) {
$d .= ','.key($second);
next($second);
}
$d = ltrim($d, ',');
$d = explode(',', $d);
foreach ($first as $the_tax) {
foreach ($d as $key => $v) {
if (in_array($v, $first)) {
$t = $second[$v];
}
}
echo $t.'<br>';
}
To be honsest, if you wouldn't explain your goal, I wouldn't even understand what you're trying to do by your code. Try like this:
<?php
$first = array('location', 'genre', 'studio', 'Lord_Of_the_Rings');
$second = array(
'location' => 1,
'genre' => 2,
'studio' => 3,
'Lord_Of_the_Rings' => 4
);
$intersect = array_intersect($first, array_keys($second));
foreach($intersect as $key)
echo $second[$key];
?>
You should move/add add an echo statement into the block where you assign the value of $t, maybe this way:
foreach ($first as $the_tax) {
foreach ($d as $key => $v) {
if (in_array($v, $first)) {
$t = $second[$v];
echo $t.' ';
}
}
echo '<br>';
}
you can flip the keys in second array, and then take the intersection of the 2. something along these lines
<?php
$first = array('location', 'genre', 'studio', 'Lord_Of_the_Rings');
$second = array(
'location' => 1,
'genre' => 2,
'studio' => 3,
'Lord_Of_the_Rings' => 4
);
$flipped = array_flip($second);
print implode(' ',array_keys(array_intersect($flipped, $first)));
?>
Related
How to check two arrays and search for matching keys and merge the values of the 1st array with the matching keys of the second array.Please help me as I'm new to this.
example :
1st array = {id => 11,name => 'name',age => 18 }
2nd array = {id,name,age,school}
I want to get the result by adding the matching values to the 2nd array
2nd array = {id => 11,name => 'name',age => 18,school => }
try this
$a = ['id' => 11,'name' => 'name','age' => 18];
$b = array_flip(['id','name','age','school']);
foreach($b as $key => &$value){
$value = '';
}
$result = array_merge($b, $a);
One of the simple way is looping
$first= array('id' => 11,'name' => 'name','age' => 18 );
$second = array('id','name','age','school');
foreach ($second as $value) {
if(isset($first[$value])){
$final[$value] = $first[$value];
}
};
print_r($final);
Second Array flip and array merge
$first = ['id' => 11,'name' => 'name','age' => 18];
$second= array_flip(['id','name','age','school']);
foreach($second as $key => s$value){
$value = '';
}
$result = array_merge($second, $first);
print_r($result);
Use array_merge
<?php
$array1 = array('id' => '11', 'name' => 'name', 'age' => 18);
$array2 = array('id','name','age','school');
$array3 = array_merge(array_fill_keys($array2, null), $array1);
print_r($array3);
?>
I have an array.
$a = array(
0 => 1,
1 => 1,
2 => 2,
3 => 3,
4 => 1
);
How to get unique array like this?
$result = array_My_unique($a);
print_r($result);
Output:
$a = array(
0 => 1,
1 => 2,
2 => 3,
3 => 1
);
Thank!
Assuming you are trying to avoid duplicates that are immediately next to each other:
function array_my_unique($a = array()) {
$out = array();
$curr = false;
foreach ($a as $v) {
if ($curr !== $v) {
$out[] = $v;
}
$curr = $v;
}
return $out;
}
This satisfies the assertion between input/output that you described in the question.
I have this multidimensional array and I would like to get from it only array('13', '11', '12', '10'). How can I get this?
array
0 =>
array
'id' => '13'
1 =>
array
'id' => '11'
2 =>
array
'id' => '12'
3 =>
array
'id' => '10'
for($i =0 ;$i<count($array);$i++)
{
echo $array[$i]['id'];
}
try
$values = array();
foreach($arr as $inner)
{
$values[] = $inner['id'];
}
// $values should now hold array(13, 11, 12, 10)
Try this :
$array = your array
$result = call_user_func_array('array_merge_recursive', $array);
echo "<pre>";
print_r($result['id']);
Try this :
<?php
$array=Array('0'=>Array('id'=>"1"),'1'=>Array('id'=>"2"),'2'=>Array('id'=>"3"),'4'=>Array('id'=>"4"));
$arr=Array();
for($i =0 ;$i<3;$i++)
{
$arr[$i]=$array[$i]['id'];
}
print_r(implode(',',$arr));
?>
O/p:
1,2,3
$values = array();
foreach(new \RecursiveIteratorIterator(new \RecursiveArrayIterator($arr)) as $key => $value) {
if ($key == 'id') $values[] = $value;
}
var_dump($values);
This question already has answers here:
Merge two indexed arrays of indexed arrays based on first column value
(2 answers)
Closed 5 months ago.
I need to compare two 2D arrays in PHP. The arrays look like this:
Array one
ID Name
11 Aa
11 Ab
12 Bb
13 Cc
14 Dd
15 Ee
Array two
ID Content
11 Cat
13 Dog
14 Donkey
Now I'd need to combine these two into an array like this:
ID Name Conent
11 Aa Cat
11 Ab Cat
12 Bb
13 Cc Dog
14 Dd Donkey
15 Ee
How can I accomplish this? I have had no luck with array_merge() or $array3 = $array1 + $array2;
A quick way would be to iterate over the first array and append the value from the second:
$array1 = array('11' => 'Aa', '12' => 'Bb', '13' => 'Cc', '14' => 'Dd', '15' => 'Ee');
$array2 = array('11' => 'Cat', '13' => 'Dog', '14' => 'Donkey');
$combined = array();
foreach ($array1 as $key => $val) {
$combined[$key] = $val . (isset($array2[$key]) ? ' '.$array2[$key] : '');
}
This will loop through every key/value in $array1 and add it to the $combined array. If a value in $array2 exists with the same index, it will append it to that value from $array1, separated with a space.
UPDATE: I misread the format of the arrays (again). I assumed ID was the actual index in the array, but as the example array output has both Name and Content, I'm assuming ID is an actual index string value and not the index in the array itself. To stick with the loop scenario, you can iterate through the first array and have a nested loop iterate through the second:
$array1 = array(
array('ID' => '11', 'Name' => 'Aa'),
array('ID' => '12', 'Name' => 'Bb'),
array('ID' => '13', 'Name' => 'Cc'),
array('ID' => '14', 'Name' => 'Dd'),
array('ID' => '15', 'Name' => 'Ee'),
);
$array2 = array(
array('ID' => '11', 'Content' => 'Cat'),
array('ID' => '13', 'Content' => 'Dog'),
array('ID' => '14', 'Content' => 'Donkey')
);
$combined = array();
foreach ($array1 as $arr) {
$comb = array('ID' => $arr['ID'], 'Name' => $arr['Name'], 'Content' => '');
foreach ($array2 as $arr2) {
if ($arr2['ID'] == $arr['ID']) {
$comb['Content'] = $arr2['Content'];
break;
}
}
$combined[] = $comb;
}
This will add every value in $array1 to the combined array and if, and only if, a value in $array2 contains the same ID field will it add it's Content field to the array too. This can be extended to handle any number of fields as well, either by name, or by changing the inner-if block to have $comb += $arr2; instead (which should merge all non-existing indexes).
You will have to make your own function:
function putThemTogether($array1, $array2) {
$output = array();
foreach($array1 as $key => $value) {
if (!isset($output[$key]))
$output[$key] = array();
$output[$key][] = $value;
}
foreach($array2 as $key => $value) {
if (!isset($output[$key]))
$output[$key] = array();
$output[$key][] = $value;
}
return $output;
}
To make this better you could make it take an arbitrary number of arguments.
$result = array_map (
function ($item) { return is_array($item) ? implode(' ', $item) : $item; },
array_merge_recursive($array1, $array2);
);
Note, that both arrays require string keys
Another solution for this is to use array_search and array_column (since PHP 5.5.0).
foreach ($array1 as $key => $val) {
$found_key = array_search($val['ID'], array_column($array2, 'ID'));
if ($found_key !== false) { $array1[$key]['Content'] = $array2[$found_key]['Content']; }
}
Try this I hope It'll work
function merge_two_arrays($array1,$array2) {
$data = array();
$arrayAB = array_merge($array1,$array2);
foreach ($arrayAB as $value) {
// This assumes there is a field called "id"
$id = $value['id'];
if (!isset($data[$id])) {
$data[$id] = array();
}
$data[$id] = array_merge($data[$id],$value);
}
return $data;
}
$master_array = merge_two_arrays($array1,$array2);
I have a maybe stupid question?
I have three arrays. And I want to get different values from the first and third array. I created the following code but the returned values are wrong.
function ec($str){
echo $str.'<br>';
}
$arr1 = array( array(
'letter' => 'A',
'number' => '1'
),
array(
'letter' => 'B',
'number' => '2'
),
array(
'letter' => 'C',
'number' => '3'
)
);
$arr2 = array( array(
'letter' => 'A',
'number' => '1'
),
array(
'letter' => 'B',
'number' => '2'
)
);
$arr3 = array( array(
'letter' => 'D',
'number' => '4'
),
array(
'letter' => 'E',
'number' => '5'
)
);
$mergeArr = array_merge($arr1,$arr3);
foreach ($mergeArr as $kMerge => $vMerge){
foreach ($arr2 as $val2){
if($val2['letter'] != $mergeArr[$kMerge]['letter']){
ec($mergeArr[$kMerge]['letter']);
}
}
}
The result of this code is:
A
B
C
C
D
D
E
E
The result I want:
C
D
E
Thanks in advance.
Based on the result you are looking for, this should do it:
$mergeArr = array_merge($arr1,$arr3);
$res = array_diff_assoc($mergeArr, $arr2);
var_dump($res);
See the snippet on codepad.
Try this instead of your foreach's:
$diff = array_diff($mergeArr, $arr2);
foreach( $diff as $d_k => $d_v ) {
ec($d_v['letter']);
}
If I understand what you are trying to do correctly, this function should do the job:
function find_unique_entries () {
$found = $repeated = array();
$args = func_get_args();
$key = array_shift($args);
foreach ($args as $arg) {
if (!is_array($arg)) return FALSE; // all arguments muct be arrays
foreach ($arg as $inner) {
if (!isset($inner[$key])) continue;
if (!in_array($inner[$key], $found)) {
$found[] = $inner[$key];
} else {
$repeated[] = $inner[$key];
}
}
}
return array_diff($found, $repeated);
}
Pass the key you are searching to the first arguments, then as many arrays as you like in the subsequent arguments. Returns an array of results or FALSE on error.
So your usage line would be:
$result = find_unique_entries('letter', $arr1, $arr2, $arr3);
See it working