I have 2 associative arrays, like below.
Array
(
[Turbine] => 0
[Nuts and Bolts] => 6
[Runner Blade] => 5
)
Array
(
[Nuts and Bolts] => 10
[Runner Blade] => 5
[Turbine] => 1
)
What I want to do is compare the two arrays and return ones that have the same key but a different value. Similar to array_intersect_assoc, but that returns all values that match which is not what I want. Using the examples above what I want to return is the difference between the 2 values, something like:
Array
(
[Nuts and Bolts] => 4
[Turbine] => 1
)
Something like this:
$ar1;
$ar2;
foreach ($ar1 as $k => $v) {
if (intval($ar2[$k]) != intval($v))
$ar1[$k] = abs($v - $ar2[$k]);
else
unset($ar1[$k]); // remove key with equal value
}
Try this...
$newArr = array();
foreach($arr1 as $k=>$v){
$dif = abs($arr1[$k] - $arr2[$k]);
if($dif) $newArr[$k] = $dif;
}
print '<pre>';
print_r($newArr);
This will do what you want:
array_intersect_key($array1, $array2)
$diff = array_diff_assoc($arr1, $arr2);
$result = array();
foreach(array_keys($diff) as $key){
$result[$key] = abs($arr1[$key] - $arr2[$key]);
}
var_dump($result);
Related
I have an array that looks something like this:
Array (
[0] => Array ( [country_percentage] => 5 %North America )
[1] => Array ( [country_percentage] => 0 %Latin America )
)
I want only numeric values from above array. I want my final array like this
Array (
[0] => Array ( [country_percentage] => 5)
[1] => Array ( [country_percentage] => 0)
)
How I achieve this using PHP?? Thanks in advance...
When the number is in first position you can int cast it like so:
$newArray = [];
foreach($array => $value) {
$newArray[] = (int)$value;
}
I guess you can loop the 2 dimensional array and use a preg_replace, i.e.:
for($i=0; $i < count($arrays); $i++){
$arrays[$i]['country_percentage'] = preg_replace( '/[^\d]/', '', $arrays[$i]['country_percentage'] );
}
Ideone Demo
Update Based on your comment:
for($i=0; $i < count($arrays); $i++){
if( preg_match( '/North America/', $arrays[$i]['country_percentage'] )){
echo preg_replace( '/[^\d]/', '', $arrays[$i]['country_percentage'] );
}
}
Try this:
$arr = array(array('country_percentage' => '5 %North America'),array("country_percentage"=>"0 %Latin America"));
$result = array();
foreach($arr as $array) {
$int = filter_var($array['country_percentage'], FILTER_SANITIZE_NUMBER_INT);
$result[] = array('country_percentage' => $int);
}
Try this one:-
$arr =[['country_percentage' => '5 %North America'],
['country_percentage' => '0 %Latin America']];
$res = [];
foreach ($arr as $key => $val) {
$res[]['country_percentage'] = (int)$val['country_percentage'];
}
echo '<pre>'; print_r($res);
output:-
Array
(
[0] => Array
(
[country_percentage] => 5
)
[1] => Array
(
[country_percentage] => 0
)
)
You can use array_walk_recursive to do away with the loop,
passing the first parameter of the callback as a reference to modify the initial array value.
Then just apply either filter_var or intval as already mentioned the other answers.
$array = [
["country_percentage" => "5 %North America"],
["country_percentage" => "0 %Latin America"]
];
array_walk_recursive($array, function(&$value,$key){
$value = filter_var($value,FILTER_SANITIZE_NUMBER_INT);
// or
$value = intval($value);
});
print_r($array);
Will output
Array
(
[0] => Array
(
[country_percentage] => 5
)
[1] => Array
(
[country_percentage] => 0
)
)
You could get all nemeric values by looping through the array. However I don't think this is the most efficient and good looking answer, I'll post it anyways.
// Array to hold just the numbers
$newArray = array();
// Loop through array
foreach ($array as $key => $value) {
// Check if the value is numeric
if (is_numeric($value)) {
$newArray[$key] = $value;
}
}
I missunderstood your question.
$newArray = array();
foreach ($array as $key => $value) {
foreach ($value as $subkey => $subvalue) {
$subvalue = trim(current(explode('%', $subvalue)));
$newArray[$key] = array($subkey => $subvalue);
}
}
If you want all but numeric values :
$array[] = array("country_percentage"=>"5 %North America");
$array[] = array("country_percentage"=>"3 %Latin America");
$newArray = [];
foreach ($array as $arr){
foreach($arr as $key1=>$arr1) {
$newArray[][$key1] = intval($arr1);
}
}
echo "<pre>";
print_R($newArray);
This is kind of a ghetto method to doing it cause I love using not as many pre made functions as possible. But this should work for you :D
$array = array('jack', 2, 5, 'gday!');
$new = array();
foreach ($array as $item) {
// IF Is numeric (each item from the array) will insert into new array called $new.
if (is_numeric($item)) { array_push($new, $item); }
}
I want to merge the keys of array based on values. This is my array.
Array
(
[1] => 1
[2] => 1
[3] => 1
[4] => 2
[5] => 0
[6] => 2
[7] => 2
)
I want output as
Array
(
[1,2,3] => 1
[4,6,7] => 2
[5] => 0
)
I have been brain storming entire day but couldn't find a solution. Any hint would be much appreciated.
WHAT I HAVE TRIED:
for($i=2;$i<=count($new);$i++){
if ($new[$i-1][1]==$new[$i][1]){
$same .= $new[$i-1][0].$new[$i][0];
}
}
echo $same;
But I am stucked. I am comparing the keys one by one but it's very complicated. I don't need the code. I only need the hint or logic. Anyone kind enough?
<?php
$old_arr = ["1"=>1,"2"=>1,"3"=>1,"4"=>2,"5"=>0,"6"=>2,"7"=>2];
$tmp = array();
foreach($old_arr as $key=>$value)
{
if(in_array($value, $tmp)){
$index = array_search($value, $tmp);
unset($tmp[$index]);
$tmp[$index.",".$key] = $value;
}else{
$tmp[$key] = $value;
}
}
ksort($tmp);
echo "<pre>";
print_r($tmp);
echo "</pre>";
?>
https://eval.in/529314
You can loop through array elements and create a new array with new structure. Please check the below code it may help you
$old_array = array(1=> 1,2 => 1,
3=> 1,
4 => 2,
5 => 0,
6 => 2,
7 => 2
);
$new_array = array();
foreach($old_array as $key => $value)
{
if(in_array($value,$new_array))
{
$key_new = array_search($value, $new_array);//to get the key of element
unset($new_array[$key_new]); //remove the element
$key_new = $key_new.','.$key; //updating the key
$new_array[$key_new] = $value; //inserting new element to the key
}
else
{
$new_array[$key] = $value;
}
}
print_r($new_array);
$arr = array(1 => 1, 2 => 1, 3 => 1, 4 => 2, 5 => 0, 6 => 2, 7 => 2);
$tmp = array();
foreach ($arr as $key => $val)
$tmp[$val][] = $key;
$new = array();
foreach ($tmp as $key => $val)
$new[implode(',', $val)] = $key;
First loop the original array through, creating a temporary array, where your original values are keys and values are the original keys as an array.
Then loop the temporary array, creating the new array, where the temporary array's values are imploded as keys.
There's no way to have an array of keys to a single value, but the other way around:
function flipWithKeyArray($arr){
$result = array();
foreach($arr as $key => $val){
if(!isset($result[$val]))
$result[$val] = array();
$result[$val][] = $key;
}
return $result;
}
This will flip your array and declare one array per value of your old array and then push the keys with the same value into each list.
For an array like this:
array(1=>1, 2=>1, 3=>1, 4=>2, 5=>2, 6=>2)
The result will look like this:
array(1=>array(1,2,3), 2=>array(4,5,6))
Hope it fits your need.
i am stuck at this stage of my project.
i am trying to get common values from four multidimensional arrays using array_intersect. can anyone help me with this issue ?
here are all four array:
$arr=array(array(8159),array(8140),array(8134),array( 8168),array(8178),array( 8182),array( 8183));
$arr1=array(array(8159),array(8140),array(8134),array(8165),array(8166),array(8167),array( 8168));
$arr2=array(array(566),array(265),array(8134),array(655),array(8166),array(665),array( 8168),array(656),array( 989),array( 989));
$arr3=array(array(8159),array(8140),array(8134),array(8165),array(8166),array(8167),array( 8168));
$res= array_intersect($arr,$arr1,$arr2,$arr3);
print_r($res);
If subarray contain one element always you could chage that value using array_map and current function.
$arr=array(array(8159),array(8140),array(8134),array( 8168),array(8178),array( 8182),array( 8183));
$arr1=array(array(8159),array(8140),array(8134),array(8165),array(8166),array(8167),array( 8168));
$arr2=array(array(566),array(265),array(8134),array(655),array(8166),array(665),array( 8168),array(656),array( 989),array( 989));
$arr3=array(array(8159),array(8140),array(8134),array(8165),array(8166),array(8167),array( 8168));
$arr = array_map('current', $arr); // getting first value of subarray
$arr1 = array_map('current', $arr1);
$arr2 = array_map('current', $arr2);
$arr3 = array_map('current', $arr3);
print_r($arr3);
// Array
// (
// [0] => 8159
// [1] => 8140
// [2] => 8134
// [3] => 8165
// [4] => 8166
// [5] => 8167
// [6] => 8168
// )
$res= array_intersect($arr,$arr1,$arr2,$arr3);
print_r($res);
// Array
// (
// [2] => 8134
// [3] => 8168
// )
Please check this
$arr=array(array(8159),array(8140),array(8134),array( 8168),array(8178),array( 8182),array( 8183));
$arr1=array(array(8159),array(8140),array(8134),array(8165),array(8166),array(8167),array( 8168));
$arr2=array(array(566),array(265),array(8134),array(655),array(8166),array(665),array( 8168),array(656),array( 989),array( 989));
$arr3=array(array(8159),array(8140),array(8134),array(8165),array(8166),array(8167),array( 8168));
foreach($arr as $value)
{
$a1[] = $value[0];
}
foreach($arr1 as $value)
{
$a2[] = $value[0];
}
foreach($arr2 as $value)
{
$a3[] = $value[0];
}
foreach($arr3 as $value)
{
$a4[] = $value[0];
}
$res= array_intersect($a1,$a2,$a3,$a4);
print_r($res);
I have two arrays,
$arr_1 = array(01=>5, 02=>3, 03=>2);
$arr_2 = array(01=>3, 02=>4, 03=>0);
what I want to achieve is to have a single array where the final form after adding the two arrays would be,
$arr_3 = array(01=>8, 02=>7, 03=>2);
I tried array_merge but it wasn't the solution.How would I attain the final form?
Try array_map. From the PHP Manual
array_map() returns an array containing all the elements of arr1
after applying the callback function to each one. The number of
parameters that the callback function accepts should match the number
of arrays passed to the array_map()
$arr_1 = array(01=>5, 02=>3, 03=>2);
$arr_2 = array(01=>3, 02=>4, 03=>0);
$arr_3 = array_map('add', $arr_1, $arr_2);
function add($ar1, $ar2){
return $ar1+$ar2;
}
print_r($arr_3);
OUTPUT:
Array ( [0] => 8 [1] => 7 [2] => 2 )
A for loop should handle this:
$max = count($arr_1);
$arr_3 = array();
for($i = 0; $i < $max; $i++){
$arr_3[$i] = intval($arr_1[$i]) + intval($arr_2[$i]);
}
I'm sure there are many other ways to do this, but this is the first one that came to mind. You could also do a foreach loop:
$arr_3 = array();
foreach($arr_1 as $k => $v){
$arr_3[$k] = intval($v) + intval($arr_2[$k]);
}
I'm just winging it here, the foreach is a little tricky to avoid the cartesian effects. Worth a shot though.
If you require adding elements matching by their key not by their position, you could try this:
$array1 = array(1=>5, 2=>3, 3=>2);
$array2 = array(3=>3, 2=>4, 1=>0); //unsorted array
$keys_matched = array_intersect_key ( $array1 , $array2);
foreach ($keys_matched as $key => $value) {
$result[$key] = $array1[$key] + $array2[$key];
}
print_r($result); //Displays: Array ( [1] => 5 [2] => 7 [3] => 5
You would look through both arrays and add each value of each array together then add that result to another array.
foreach($array1 as $val1) {
foreach($array2 as $val2) {
array_push($newArray, intval($val1)+ intval(val2));
}
}
This question already has answers here:
Transpose and flatten two-dimensional indexed array where rows may not be of equal length
(4 answers)
Closed 10 months ago.
How can I merge two arrays when array 1 values will be in even places and array 2 will be in odd places?
Example:
$arr1=array(11, 34,30);
$arr2=array(12, 666);
$output=array(11, 12, 34, 666,30);
This will work correctly no matter the length of the two arrays, or their keys (it does not index into them):
$result = array();
while(!empty($arr1) || !empty($arr2)) {
if(!empty($arr1)) {
$result[] = array_shift($arr1);
}
if(!empty($arr2)) {
$result[] = array_shift($arr2);
}
}
Edit: My original answer had a bug; fixed that.
try this
$arr1=array(11,34,30,35);
$arr2=array(12,666,23);
$odd= array_combine(range(0,2*count($arr1)-1,2), $arr1);
$even = array_combine(range(1,2*count($arr2)-1,2), $arr2);
$output=$odd+$even;
ksort($output);
echo "<pre>";
print_r($output);
returns
Array
(
[0] => 11
[1] => 12
[2] => 34
[3] => 666
[4] => 30
[5] => 23
[6] => 35
)
Assuming $arr1 and $arr2 are simple enumerated arrays of equal size, or where $arr2 has only one element less that $arr1.
$arr1 = array(11, 34);
$arr2 = array(12, 666);
$output = array();
foreach($arr1 as $key => $value) {
$output[] = $value;
if (isset($arr2[$key])) {
$output[] = $arr2[$key];
}
}
Go through array with more items, use loop index to access both arrays and combine them into resulting one as required...
$longer = (count($arr1) > count($arr2) ? $arr1 : $arr2);
$result = array();
for ($i = 0; $i < count($longer); $i++) {
$result[] = $arr1[i];
if ($arr2[i]) {
$result[] = $arr2[i];
} else {
$result[] = 0; // no item in arr2 for given index
}
}