How To Subtract Values From An Array In PHP? - php

I am trying to "subtract" the values of an array in php. I used array_diff but it doesn't seem to work for more than one value.
<?php
$array1 = array(1,3,7,10,7);
$array2 = array(1,7);
$result=array_diff($array1,$array2);
print_r($result);
?>
//Output//
Array ( [1] => 3 [3] => 10 )
What I would like to do is return 3,7,10 instead of excluding all 7's. Thanks in advance!

Try:
$array1 = array(1,3,7,10,7);
$removals = Array(1,7);
foreach( $removals as $remove ) {
foreach( $array1 as $key => $value ) {
if ($value === $remove ) {
unset($array1[ $key ]);
break;
}
}
}
print_r($array1); // Array ( [1] => 3 [3] => 10 [4] => 7 )
sort($array1)
print_r($array1); // Array ( [0] => 3 [1] => 7 [2] => 10 )

based on thelastshadows post but shorter and may faster because only one foreach
$array1 = array(1,3,7,10,7);
$removals = Array(1,7);
foreach( $removals as $remove ) {
unset($array1[array_search($remove,$array1)]);
}
sort($array1);
print_r($array1);

Related

php compare multidimensional array equal

Array 1
Array
(
[0] => Array
(
[prid] => 110
[size_id] => 24
)
[1] => Array
(
[prid] => 117
[size_id] => 24
)
[2] => Array
(
[prid] => 174
[size_id] => 24
)
)
Array 2
Array
(
[0] => Array
(
[prid] => 174
[size_id] => 24
)
[1] => Array
(
[prid] => 174
[size_id] => 25
)
[2] => Array
(
[prid] => 163
[size_id] => 24
)
)
I have 2 multidimensional arrays. I want to compare both arrays and resultant arrays are equal in both.
(i.e) The answer is
[prid] => 174
[size_id] => 24
Note:- i am using array_intersect_assoc(),but not working
How can we retrieve this???
Please tell the answer to this
You can use foreach() and array_column() to compare second array value with first array
$final_array = [];
foreach($array2 as $arr){
if(in_array($arr['prid'],array_column($array1,'prid')) && in_array($arr['size_id'],array_column($array1,'size_id'))){
$final_array[$arr['prid']] = $arr;
}
}
$final_array = array_values($final_array);
print_r($final_array);
Output:- https://eval.in/979112
Another easier solution using array_intersect() and array_column()
$final_array = [];
$common_array = array_intersect (array_column($array1,'prid'),array_column($array2,'prid'));
foreach($common_array as $key=>$val){
$final_array[] = $array1[$key];
}
print_r($final_array);
Output:-https://eval.in/979135
$new_array = array();
foreach($array1 as $value1){
foreach($array2 as $value2){
if($value1['prid'] == $value2['prid'] && $value1['size_id'] == $value2['size_id']){
$new_array[] = $value1;
}
}
}
echo print_r($new_array);
You can get this done by using couple of array function and a foreach loop.
Try like this:-
$array1=[
['prid'=>110,'size_id'=>24],
['prid'=>117,'size_id'=>24],
['prid'=>174,'size_id'=>24],
];
$array2=[
['prid'=>174,'size_id'=>24],
['prid'=>174,'size_id'=>25],
['prid'=>163,'size_id'=>24]
];
$prid = array_intersect(array_column($array1,'prid'),array_column($array2,'prid'));
$size_id = array_intersect(array_column($array1,'size_id'),array_column($array2,'size_id'));
$array3 = array_merge($array1,$array2);
$result=[];
foreach ($array3 as $data){
if(in_array($data['prid'],$prid) && in_array($data['size_id'],$size_id)){
$result = $data;
break;
}
}
or like this
$result=[];
foreach ($array1 as $data1){
foreach ($array2 as $data2){
if($data1['prid']==$data2['prid'] && $data1['size_id']==$data2['size_id']){
$result = $data1;
break;
}
}
}
It will give o/p like this

Explode array's data and make new array

I have this array:
Array
(
[0] => Array
(
[0] => 1
[1] => a,b,c
)
[1] => Array
(
[0] => 5
[1] => d,e,f
)
)
I want the final array to be this:
Array
(
[0] => Array
(
[0] => 1
[1] => a
)
[1] => Array
(
[0] => 1
[1] => b
)
[2] => Array
(
[0] => 1
[1] => c
)
[3] => Array
(
[0] => 5
[1] => d
)
[4] => Array
(
[0] => 5
[1] => e
)
[5] => Array
(
[0] => 5
[1] => f
)
)
This is what I did:
<?php
$array = array(array(1,"a,b,c"),array(5,"d,e,f"));
$temp=array();
$count = 0;
foreach($array as $arr){
$rows = explode(",",$arr[1]);
foreach($rows as $row){
$temp[$count] = $arr;
$temp[$count][1] = $row;
$count++;
}
}
print_r($temp);
?>
This totally works but I was wondering if there was a better way to do this. This can be very slow when I have huge data.
Try like this way...
<?php
$array = array(array(1,"a,b,c"),array(5,"d,e,f"));
$temp=array();
$count = 0;
foreach($array as $arr){
$rows = explode(",",$arr[1]);
foreach($rows as $row){
$temp[$count][] = $arr[0];
$temp[$count][] = $row;
$count++;
}
}
/*print "<pre>";
print_r($temp);
print "<pre>";*/
?>
Here's a functional approach:
$result = array_merge(...array_map(function(array $a) {
return array_map(function($x) use ($a) {
return [$a[0], $x];
}, explode(",", $a[1]));
}, $array));
Try it online.
Or simply with two loops:
$result = [];
foreach ($array as $a) {
foreach (explode(",", $a[1]) as $x) {
$result[] = [$a[0], $x];
}
}
Try it online.
Timing these reveals that a simple loop construct is ~8 times faster.
functional: 4.06s user 0.08s system 99% cpu 4.160 total
loop: 0.53s user 0.05s system 102% cpu 0.561 total
If you need other way around,
$array = array(array(1, "a,b,c"), array(5, "d,e,f"));
$temp = [];
array_walk($array, function ($item, $key) use (&$temp) {
$second = explode(',', $item[1]);
foreach ($second as $v) {
$temp[] = [$item[0], $v];
}
});
print_r($temp);
array_walk — Apply a user supplied function to every member of an array
Here is working demo.

How to get the difference of two multidimensional arrays in php?

I want to get the difference of two multidimensional arrys, e.g.,
First Array:
Array
(
[qtr_selected] => Array
(
[partner_q_m_p__2031] => Array
(
[0] => q1
[1] => q2
)
[partner_q_m_p__2032] => Array
(
[0] => q1
)
)
)
Second Array:
Array
(
[qtr_completed] => Array
(
[partner_q_m_p__2031] => Array
(
[0] => q1
)
)
)
how do i get the difference of array1 & array2 as given below:
Array
(
[qtr_final] => Array
(
[partner_q_m_p__2031] => Array
(
[0] => q2
)
[partner_q_m_p__2032] => Array
(
[0] => q1
)
)
)
Tried array_diff() function but not getting array1 as difference except array2, i want array1 after subtracting array2 from it.
Simply make a custom function like as
function check_diff($arr1, $arr2){
$check = (is_array($arr1) && count($arr1)>0) ? true : false;
$result = ($check) ? ((is_array($arr2) && count($arr2) > 0) ? $arr2 : array()) : array();
if($check){
foreach($arr1 as $key => $value){
if(isset($result[$key])){
$result[$key] = array_diff($value,$result[$key]);
}else{
$result[$key] = $value;
}
}
}
return $result;
}
$result['qtr_final'] = check_diff($a1['qtr_selected'],$a2['qtr_completed']);
print_r($result);
Try as below :
$a1 = Array
(
'qtr_selected' => Array
(
'partner_q_m_p__2031' => Array
(
'0' => 'q1',
'1' => 'q2',
),
'partner_q_m_p__2032' => Array
(
'0' => 'q1'
)
)
);
$a2 = Array
(
'qtr_completed' => Array
(
'partner_q_m_p__2031' => Array
(
'0' => 'q1'
)
)
);
$result['qtr_final'] = check_diff_multi($a1['qtr_selected'],
$a2['qtr_completed']);
print '<pre>';
print_r($result);
print '</pre>';
function check_diff_multi($array1, $array2){
$result = array();
foreach($array1 as $key => $val) {
if(isset($array2[$key])){
if(is_array($val) && $array2[$key]){
$result[$key] = check_diff_multi($val, $array2[$key]);
}
} else {
$result[$key] = $val;
}
}
return $result;
}
You can get difference of array1 and array2 by using this:
<?
// array 1
$array1['qtr_selected']['partner_q_m_p__2031'] = array('q1','q2');
$array1['qtr_selected']['partner_q_m_p__2032'] = array('q1');
// array 2
$array2['qtr_completed']['partner_q_m_p__2031'] = array('q1');
$removalArr = array();
foreach ($array2 as $key1 => $value1) {
foreach ($value1 as $key2 => $value2) {
$removalArr = $value2; // get last value of removal array
}
}
$finalArr = array();
foreach ($array1 as $key1 => $value1) {
foreach ($value1 as $key2 => $value2) {
// check difference if available,
// if difference available use array_diff else use normal.
$finalArr['qtr_final'][$key2] = (array_diff($value2,$removalArr) ? array_diff($value2,$removalArr) : $value2);
}
}
echo "<pre>";
print_r($finalArr);
?>
Result:
Array
(
[qtr_final] => Array
(
[partner_q_m_p__2031] => Array
(
[1] => q2
)
[partner_q_m_p__2032] => Array
(
[0] => q1
)
)
)

PHP Sort Mega-Array by Value

I am looking for some advices how could I sort this kind of Array by 'variant_name' key.
Because Array is really huge I minified it to the looking result state.
...
$filter[2413][1][81][sub_id] = 1;
$filter[2413][1][81][variant_id] = 81;
$filter[2413][1][81][variant_name] = 'Banana';
$filter[2413][2][87][sub_id] = 2;
$filter[2413][2][87][variant_id] = 87;
$filter[2413][2][87][variant_name] = 'Apple';
$filter[2413][3][32][sub_id] = 3;
$filter[2413][3][32][variant_id] = 32;
$filter[2413][3][32][variant_name] = 'Carrot';
...
Keys $filter[x][x][x] are not sequential.
I have tried the sort function I used before but it doesn't work with this kind of Array:
function array_sort_by_column(&$arr, $col, $dir = SORT_ASC) {
$sort_col = array();
foreach ($arr as $key=> $row) {
$sort_col[$key] = $row[$col];
}
array_multisort($sort_col, $dir, $arr);
}
array_sort_by_column($filter[][][], 'variant_name');
My target is modify array by sorting 'variant_name' to 'Apple', 'Banana', 'Carrot' accordingly keeping the array structure.
It's a working code tested from given examples.
Note that my codes still can be optimized, etc. Just take it as my advice.
TL;DR = Use usort().
function mySort($a,$b)
{
$av = "";
$bv = "";
foreach($a as $ak)
$av = $ak['variant_name'];
foreach($b as $bk)
$bv = $bk['variant_name'];
if($av[0] < $bv[0])
return false;
else return true;
}
How to use it? You have to specify which first level array to sort.
usort($filter['2413'],"mySort");
Then the result I got is:
Array
(
[2413] => Array
(
[0] => Array
(
[87] => Array
(
[sub_id] => 2
[variant_id] => 87
[variant_name] => Apple
)
)
[1] => Array
(
[81] => Array
(
[sub_id] => 1
[variant_id] => 81
[variant_name] => Banana
)
)
[2] => Array
(
[32] => Array
(
[sub_id] => 3
[variant_id] => 32
[variant_name] => Carrot
)
)
)
)

help needed restructuring a php array

I was wondering if anyone could help me restructure a predefined php array. The output of my current array is:
Array
(
[71-ctns] => 1
[71-units] => 1
[308-units] => 1
[305-ctns] => 1
[306-units] => 2
)
And I would like it to look like:
Array
(
[71] => Array
(
[ctns] => 1
[units] => 1
)
[308] => Array
(
[units] => 1
)
[305] => Array
(
[ctns] => 1
)
[306] => Array
(
[units] => 2
)
)
Is this possible?
This should do it
$merged = array();
foreach($a as $k=>$v){
$t = explode('-',$k);
$id = intval($t[0]);
if(!array_key_exists($id, $merged))
$merged[$id] = array();
$merged[$id][$t[1]] = $v;
}
EDIT:
Sorry you should use explode instead of split.
Yes, but you need to loop (note: array_map can also work, but this example is more explicit):
$fin = array();
foreach( $complex as $item => $val )
{
$pieces = explode('-', $item);
$fin[$pieces[0]] = isset($fin[$pieces[0]])?:array();
$fin[$pieces[0]][$pieces[1]] = $val;
}
Find below code to restructure a predefined php array
<?php
$newArray=array();
$result = array("71-ctns"=>1,"71-units"=>1,"308-ctns"=>1,"308-units"=>1,"305-units"=>1,"306-units"=>2);
if(is_array($result) && count($result)>0) {
foreach($result as $key=>$val) {
$getKeyArray = explode("-",$key);
$newArray[$getKeyArray[0]][$getKeyArray[1]] =$val;
}
}
print"<pre>";
print_r($newArray);
?>

Categories