Is there a way to combine boolean arrays:
$array1: ['prop1'=>T, 'prop2'=>F, 'prop3'=>T, 'prop4'=>F, 'prop5'=>T]
$array2: ['prop1'=>T, 'prop2'=>F, 'prop3'=>F, 'prop4'=>T]
Into
$array3: ['prop1'=>T, 'prop2'=>F, 'prop3'=>T, 'prop4'=>T, 'prop5'=>T]
Using the OR comparison?
I thought using $array3 = $array1 | $array2 would work but it returns a single value.
I feel like this could be a duplicate but I failed to find the same question on SO.
While each array have the same key you can use foreach loop to loop through the first array check if equally then you set the key and value to result array else if not equally then use the one with true value
$result=array();
foreach($array1 as $key=>$value){
if($array1[$key]==$array2[$key] || $array2==undefined){
$result[$key]=$value;
}
else{
$result[$key]=($array1[$key]==True)?$array1[$key] : $array2[$key];
}
}
Then loop through second array to see if the key is undefined in first to add the key value from second array
foreach($array2 as $key=>$value){
if ($array1[$key]==undefined){
$result[$key]=$value;
}
}
This is the shortest solution I can think of. And it's really not that complicated :). First we add the two arrays to make sure all keys exist in $result. Then we use the array_walk to perform the logical operation.
We need 3 arguments. The first is the $result variable we want to manipulate.
The third argument gets passed to our callback. We again use an array sum to ensure all keys are set, but this time $array2 gets the precedence.
The second is our callback. We get each value from the preliminary result by reference (&), each key by value, and our wish as a third parameter. The function itself is really simple we just set $v to whatever operation we want to implement. || for OR, && for AND or xor for XOR (but xor needs additional parentheses, see Operator precedence).
Demo
$array1 = ['prop1'=>TRUE, 'prop2'=>FALSE, 'prop3'=>TRUE, 'prop4'=>TRUE];
$array2 = ['prop1'=>TRUE, 'prop2'=>TRUE, 'prop3'=>FALSE, 'prop5'=>FALSE];
$result = $array1 + $array2;
array_walk($result, function(&$v, $k, $a){
$v = $v || $a[$k]; //Here you can change the operation
}, $array2+$array1);
var_dump($result);
Related
I have a multi-D array like so:
array ( 'JD'=>2457002.50, 67.618536),
array ( 'JD'=>2457003.50, 67.619705),
array ( 'JD'=>2457004.50, 67.620938)....
I have a value say:
$MyJD = 2457003.9553;
I would like to find the value in the array, and if not, match the closest number to the array in question and return the the next index (which i'm assuming is [1])
I was thinking to do an array_search, but it's not going to find the exact number, I want the closest number to $MyValue?
This won't return the index but will return the proper array:
array_multisort(array_map(function($v) use($MyJD) {
return abs($v['JD'] - $MyJD);
}, $array), $array);
$result = reset($array);
Calculate the difference between each JD value and $MyJD
Sort on the difference (sorting the original) and get the lowest (first) one
Alternately, you could combine using the difference as the key and then sort on the keys:
$array = array_combine(array_map(function($v) use($MyJD) {
return abs($v['JD'] - $MyJD);
}, $array), $array);
ksort($array);
$result = reset($array);
Maybe someone will post a good array_reduce answer.
Do bucle put new array with key difference between
In this way you will have array ordered by difference
In each iteration
$myarray[myvalue - yourvalueinbucle] if -1 this key then ×-1 and how value your enter iterator of bucle, then your value for this key = your line multiarrayvalue in for each iterator
I have an array in the array, and I want to make it just one array, and I can easily retrieve that data
i have some like
this
but the coding only combines the last value in the first array, not all values
is it possible to make it like that?
so that I can take arrays easily
I would make use of the unpacking operator ..., combined with array_merge:
$array['test2'] = array_merge(...array_merge(...$array['test2']));
In your case you need to flatten exactly twice, if you try to do it one time too much it will fail due to the items being actual arrays themselves (from PHP's perspective).
Demo: https://3v4l.org/npnTi
Use array_merge (doc) and ... (which break array to separate arrays):
function flatten($arr) {
return array_merge(...$arr);
}
$arr = [[["AAA", "BBB"]], [["CCC"]]];
$arr = flatten(flatten($arr)); // using twice as you have double depth
In your case, $arr is $obj["test2"]. If your object is json cast it to array first and if it is a string use json_decode
Live example: 3v4l
if you have a array then you can use the below code
if(!empty($array['test2'])){
$newarray = array();
foreach ($array['test2'] as $arrayRow) {
$newarray = array_merge($newarray,$arrayRow);
}
$array['test2'] = $newarray;
}
I have the following two arrays:
$array_one = array('colorZero'=>'black', 'colorOne'=>'red', 'colorTwo'=>'green', 'colorThree'=>'blue', 'colorFour'=>'purple', 'colorFive'=>'golden');
$array_two = array('colorOne', 'colorTwo', 'colorThree');
I want an array from $array_one which only contains the key-value pairs whose keys are members of $array_two (either by making a new array or removing the rest of the elements from $array_one)
How can I do that?
I looked into array_diff and array_intersect, but they compare values with values, and not the values of one array with the keys of the other.
As of PHP 5.1 there is array_intersect_key (manual).
Just flip the second array from key=>value to value=>key with array_flip() and then compare keys.
So to compare OP's arrays, this would do:
$result = array_intersect_key( $array_one , array_flip( $array_two ) );
No need for any looping the arrays at all.
Update
Check out the answer from Michel: https://stackoverflow.com/a/30841097/2879722. It's a better and easier solution.
Original Answer
If I am understanding this correctly:
Returning a new array:
$array_new = [];
foreach($array_two as $key)
{
if(array_key_exists($key, $array_one))
{
$array_new[$key] = $array_one[$key];
}
}
Stripping from $array_one:
foreach($array_one as $key => $val)
{
if(array_search($key, $array_two) === false)
{
unset($array_one[$key]);
}
}
Tell me if it works:
for($i=0;$i<count($array_two);$i++){
if($array_two[$i]==key($array_one)){
$array_final[$array_two[$i]]=$array_one[$array_two[$i]];
next($array_one);
}
}
This question already has answers here:
What's the difference between array_merge and array + array? [duplicate]
(9 answers)
Closed 7 years ago.
When I use array_merge() with associative arrays I get what I want, but when I use them with numerical key arrays the keys get changed.
With + the keys are preserved but it doesn't work with associative arrays.
I don't understand how this works, can anybody explain it to me?
Because both arrays are numerically-indexed, only the values in the first array will be used.
The + operator returns the right-hand array appended to the left-hand array; for keys that exist in both arrays, the elements from the left-hand array will be used, and the matching elements from the right-hand array will be ignored.
http://php.net/manual/en/language.operators.array.php
array_merge() has slightly different behavior:
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. Values in the input array with numeric keys will be renumbered with incrementing keys starting from zero in the result array.
http://php.net/manual/en/function.array-merge.php
These two operation are totally different.
array plus
Array plus operation treats all array as assoc array.
When key conflict during plus, left(previous) value will be kept
null + array() will raise fatal error
array_merge()
array_merge() works different with index-array and assoc-array.
If both parameters are index-array, array_merge() concat index-array values.
If not, the index-array will to convert to values array, and then convert to assoc array.
Now it got two assoc array and merge them together, when key conflict, right(last) value will be kept.
array_merge(null, array()) returns array() and got a warning said, parameter #1 is not an array.
I post the code below to make things clear.
function array_plus($a, $b){
$results = array();
foreach($a as $k=>$v) if(!isset($results[$k]))$results[$k] = $v;
foreach($b as $k=>$v) if(!isset($results[$k]))$results[$k] = $v;
return $results;
}
//----------------------------------------------------------------
function is_index($a){
$keys = array_keys($a);
foreach($keys as $key) {
$i = intval($key);
if("$key"!="$i") return false;
}
return true;
}
function array_merge($a, $b){
if(is_index($a)) $a = array_values($a);
if(is_index($b)) $b = array_values($b);
$results = array();
if(is_index($a) and is_index($b)){
foreach($a as $v) $results[] = $v;
foreach($b as $v) $results[] = $v;
}
else{
foreach($a as $k=>$v) $results[$k] = $v;
foreach($b as $k=>$v) $results[$k] = $v;
}
return $results;
}
is there a command to know if an array has their keys as string or plain int?
Like:
$array1 = array('value1','value2','value3');
checkArr($array1); //> Returns true because there aren't keys as string
And:
$array2 = array('key1'=>'value1','key2'=>'value2','value3');
checkArr($array2); //> Returns false because there are keys as string
Note: I know I can parse all the array to check it.
The "compact" version to test this is:
$allnumeric =
array_sum(array_map("is_numeric", array_keys($array))) == count($array);
#Gumbo's suggestion is 1 letter shorter and could very well be a bit speedier for huge arrays:
count(array_filter(array_keys($array), "is_numeric")) == count($array);
You can use array_keys to obtain the keys for the array and then analyse the resultant array.
look at array_keys() if values are int - you got ints if strings -> strings
If you want to check the array's keys, it would be probably better to use something like this:
reset($array);
while (($key = key($array)) !== null) {
// check the key, for example:
if (is_string($key)) {
// ...
}
next($array);
}
This will be most performant, as there are no extraneous copies made of variables that you are not going to use.
On the other hand, this way is probably the most readable and makes the intent crystal clear:
$keys = array_keys($array);
foreach($keys as $key) {
// check the key, for example:
if (is_string($key)) {
// ...
}
}
Take your pick.
Important note:
Last time I checked, PHP would not let you have keys which are string representations of integers. For example:
$array = array();
$array["5"] = "foo";
echo $array[5]; // You might think this will not work, but it will
So keep that in mind when you are checking what the types of such keys are: they might have been created as strings, but PHP will have converted them to integers behind the scenes.