I like to compare an array from a database against another array to generate a new array of missing ids using isset or array_key_exists. Here is the array from my database I am creating.
foreach ($listings as $listing) {
$local_ids[$listing['id']] = 'true';
}
$local_ids = array(
'567' => true,
'568' => true,
'569' => true,
'570' => true,
'571' => true,
'572' => true,
'573' => true
);
$new_ids = array(
'568',
'569',
'572',
'573',
'574',
'575',
'576',
'577'
);
Taking the above two arrays, I would like to cycle through them to give me a result that 567, 570, 571 have been removed.
I altered the $new_ids as this list may or may not contain ids that are new and not in $local_ids. These can be ignored, I just need the ones removed.
i know a method which goes like this
<?php
$a1 = array("a" => "one", "two", "three", "four");
$a2 = array("b" => "one", "two", "three");
$result = array_diff($array1, $array2);
print_r($result);
?>
or
<?php
$a1 = array("a" => "one", "b" => "two", "c" => "three", "four");
$a2 = array("a" => "one", "two", "three");
$result = array_diff_assoc($array1, $array2);
print_r($result);
?>
Related
I have for example three arrays in one array:
$foo = [
"id" => [1, 3, 8],
"name" => ['one', 'three', 'eight'],
"isLarge" => [false, true, true]
];
I want simple combine these arrays as exactly the reverse operation to array_column, basically I want to obtain:
$bar = [[
"id" => 1,
"name" => "one",
"isLarge" => false
], [
"id" => 3,
"name" => "three",
"isLarge" => true
], [
"id" => 8,
"name" => "eight",
"isLarge" => true
]];
Thanks in advance!
One solution would be:
$bar = [];
for ($i = 0; $i < count($foo['id']); $i++)
$bar[] = [
"id" => $foo["id"][$i],
"name" => $foo["name"][$i],
"isLarge" => $foo["isLarge"][$i]
];
But this seems a bit cumbersome.
You can avoid hardcoding the column names by looping over the first row of your array, and then using a combination of array_combine and array_column to transpose it:
$keys = array_keys($foo);
$bar = [];
foreach(array_keys($foo[$keys[0]]) as $columnNumber) {
$bar[] = array_combine($keys, array_column($foo, $columnNumber));
}
This takes each vertical "slice" of your 2d array, and uses each one to create a row in the output.
See https://3v4l.org/nscrh for a demo
On the off-chance that your resulting array doesn't need the column names and all you need is a pure transposition, you can use a much quicker option:
$bar = array_map(null, ...array_values($foo));
I want to go from these arrays:
$array1 = ["x", "y", "z"];
$array2 = ["a","b"];
$array3 = ["1","2","3","4","5","6"];
To this array:
$arrayResult =
array(
array("x" => array("a" => array(1,2,3,4,5,6),
"b" => array(1,2,3,4,5,6)),
"y" => array("a" => array(1,2,3,4,5,6),
"b" => array(1,2,3,4,5,6)),
"z" => array("a" => array(1,2,3,4,5,6),
"b" => array(1,2,3,4,5,6)))
);
I tried to make this combined array with cartesian product approaches, but no satisfying result so far.
Here is another solution without using any loop:
$array1 = ["x", "y", "z"];
$array2 = ["a","b"];
$array3 = ["1","2","3","4","5","6"];
$result = array_combine(
$array1,
array_fill(
0,
count($array1),
array_combine(
$array2,
array_fill(0, count($array2), $array3)
)
)
);
print_r($result);
Here is the demo
use array_fill_keys twice to get the result
$result = array_fill_keys(
$array1,
array_fill_keys($array2, $array3)
);
Demo on eval.in
I have an array like below.
$a = array(
array("id" => 1, "name" => "njx", "count" => 0),
array("id" => 2, "name" => "peter", "count" => 4),
array("id" => 3, "name" => "jeffry", "count" => 2),
array("id" => 4, "name" => "adam", "count" => 6)
);
and applied filter like this.
$fa = array_filter($a, function ($item) {
return ($item["count"] > 0);
});
then i applied usort on variable $fa. After that i loop through $fa and assigned some values, but they are not get reflected in variable $a.
something like below,
usort($fa, 'comp');
foreach ($fa as &$t) {
$t["score"] = 120;
}
var_dump($a); //this doesn't contain "score" field.
So my questions is how to get filtered array with original array reference?
array_filter returns a new array and not a reference, thats why any changes applied to $fa wont be reflected in $a.
Instead of using array_filter you could use a foreach loop like this:
foreach($a as &$t) {
if($t['count'] > 0) {
$t['score'] = 120;
}
}
And then sort using usort.
I use this code :
$new = array(
"123" => "a",
"456" => "b"
);
$old = array(
"123" => "a",
"456" => "b"
);
then the $new array become like this:
$new = array(
"456" => "b",
"123" => "c",
"789" => "e"
);
as you see the count of $new array increased and the order of elements changed and the value at key 123 also changed. I need to compare the $new array against the $old array and catch only the change made on the value at key 123 without caring about the order and the count of elements. I tried:
$result = array_diff( $new, $old );
print_r( $result );
output :
Array ( [123] => c [789] => e )
UPDATE. quite confusing. now I think we got it
$old = array(
"123" => "a",
"456" => "b"
);
$new = array(
"456" => "b",
"123" => "c", // catch this (element in old array that is changed)
"789" => "e"
);
$new2 = array();
foreach ($new as $key => $new_val)
{
if (isset($old[$key])) // belongs to old array?
{
if ($old[$key] != $new_val) // has changed?
$new2[$key] = $new[$key]; // catch it
}
}
// output $new2:
array (
123 => 'c',
)
You first of all want to have those elements of $new that are changed compared to $old (see array_diff_assoc):
$changed = array_diff_assoc($new, $old);
Of that result you want to have only those elements that have their key in $old (see array_intersect_key):
$result = array_intersect_key($changed, $old);
And that's it. You can wrap that into each other if it helps:
array_intersect_key(array_diff_assoc($new, $old), $old);
Result is:
array(1) {
[123] =>
string(1) "c"
}
Full example (Demo):
$old = array(
"123" => "a",
"456" => "b"
);
$new = array(
"456" => "b",
"123" => "c", // catch only the change made on the value at key 123
"789" => "e"
);
$changed = array_diff_assoc($new, $old);
$result = array_intersect_key($changed, $old);
var_dump($result);
Just a final note: There are many array functions in PHP. It's worth to go through the list and look what is fitting because most often you only need one or two of them to get things like these done.
You use this code for your requirements
<?php
function key_compare_func($key1, $key2)
{
if ($key1 == $key2)
return 0;
else if ($key1 > $key2)
return 1;
else
return -1;
}
$array1 = array('blue' => 1, 'red' => 2, 'green' => 3, 'purple' => 4);
$array2 = array('green' => 5, 'blue' => 6, 'yellow' => 7, 'cyan' => 8);
var_dump(array_intersect_ukey($array1, $array2, 'key_compare_func'));
?>
I have two array which i want to merge in a specific way in php.
So i need your help in helping me with it as i tried and failed.
So say i have two arrays:
$array1= array(
"foo" => 3,
"bar" => 2,
"random1" => 4,
);
$array2= array(
"random2" => 3,
"random3" => 4,
"foo" => 6,
);
Now when during merging i would like the common key's values to be added.
So like foo exists in array1 and in array2 so when merging array1 with array 2 i should get "foo" => "9"
I better illustration would be the final array which looks like this:
$array1= array(
"foo" => 9,
"bar" => 2,
"random1" => 4,
"random2" => 3,
"random3" => 4,
);
So again i would like the values of the common keys to be added together and non common keys to be added to array or a new array
I hope i was clear enough
Thanks,
Vidhu
Something like that:
function mergeValues() {
$result = array();
$arraysToMerge = func_get_args();
foreach ($arraysToMerge as $array) {
foreach($array as $key => $value) {
$result[$key] += $value;
}
}
return $result;
}
$res = mergeValues($array1, $array2, $array3); // Can pass any ammount of arrays to a function.
foreach($array1 as $k => $v)
{
If (isset($array2[$k]))
$array1[$k] += $array2[$k];
}
foreach($array2 as $k => $v)
{
If (!isset($array1[$k]))
$array1[$k] = $array2[$k];
}