How do i split this array into two? - php

I have this array.
Array
(
[name] => Array
(
[isRequired] => 1
[isBetween] => 1
[isAlphaLower] =>
[isLength] =>
)
[email] => Array
(
[isEmail] => 1
)
[pPhone] => Array
(
[isPhone] =>
)
)
i want to split the array into two.
1. array with all boolean value true
Array
(
[name] => Array
(
[isRequired] => 1
[isBetween] => 1
)
[email] => Array
(
[isEmail] => 1
)
)
2. array with all boolean value false
Array
(
[name] => Array
(
[isAlphaLower] =>
[isLength] =>
)
[pPhone] => Array
(
[isPhone] =>
)
)
How do i do it?
thank you..

initialize the two new arrays
foreach the input array
foreach the inner array of each input array entry
according to the value set the one or the other of the two new arrays
done.
Example:
$arrayTrue = $arrayFalse = arrray(); # 1
foreach($arrayInput as $baseKey => $inner) # 2
foreach($inner as $key => $value) # 3
if ($value) $arrayTrue[$basekey][$key] = $value; # 4
else $arrayFalse[$basekey][$key] = $value;

function is_true($var) {
return $var;
}
function is_false($var) {
return !$var;
}
$result_true = array();
$result_false = array();
foreach ($array as $k => $a) {
$result_true[$k] = array_filter($a, 'is_true');
$result_false[$k] = array_filter($a, 'is_false');
};
or
$result_true = array();
$result_false = array();
foreach ($array as $k => $a) {
$result_true[$k] = array_filter($a);
$result_false[$k] = array_filter($a, function ($x) { return !$x; } );
};

As your array is a 2 level array, you will need to use 2 loops.
$trueValues = array();
$falseValues = array();
foreach($input AS $key=>$firstLevelValue) {
foreach($firstLevelValue AS $key2=>$secondLevelValue) {
if ($secondLevelValue)
$trueValues[$key][$key2] = $secondLevelValue;
else
$falseValues[$key][$key2] = $secondLevelValue;
}
}
A 3 level array would be:
$trueValues = array();
$falseValues = array();
foreach($input AS $key=>$firstLevelValue) {
foreach($firstLevelValue AS $key2=>$secondLevelValue) {
foreach($secondLevelValue AS $key3=>$thirdLevelValue) {
if ($thirdLevelValue)
$trueValues[$key][$key2][$key3] = $thirdLevelValue;
else
$falseValues[$key][$key2][$key3] = $thirdLevelValue;
}
}
}

Related

remove duplicate items from object php

{"id":34,"first_name":"xus"}
{"id":34,"first_name":"xus"}
{"id":4,"first_name":"ABC"}
{"id":4,"first_name":"ABC"}
$newlist = [];
$values = [];
foreach ($appointment_list as $key => $value) {
# code...
$values[] = $value['users'];
foreach($values as $val){
$newlist[$val->id]=$values;
}
unset($newlist[$key][$values]);
}
I want to remove duplicate value from object show distinct value base on id and want to count duplicate exist of each id
Expected
id 34 has 2 duplicate
and it should return one object
{"id":34,"first_name":"xus", "count":2}
something like that
You can use array_reduce
$arr = array(
array("id" => 34,"first_name" => "xus"),
array("id" => 34,"first_name" => "xus"),
array("id" => 4,"first_name" => "ABC"),
array("id" => 4,"first_name" => "ABC"),
);
$result = array_reduce($arr, function($c, $v){
if ( !isset( $c[$v["id"]] ) ) {
$c[$v["id"]] = $v;
$c[$v["id"]]["count"] = 1;
} else {
$c[$v["id"]]["count"]++;
}
return $c;
}, array());
$result = array_values( $result );
echo "<pre>";
print_r( $result );
echo "</pre>";
This will result to:
Array
(
[0] => Array
(
[id] => 34
[first_name] => xus
[count] => 2
)
[1] => Array
(
[id] => 4
[first_name] => ABC
[count] => 2
)
)
The simplest way of doing this is to create an empty array and map your objects using "id" as a key.
Here's the working snippet
<?php
$objectsRaw = [];
$objectsRaw[] = '{"id":34,"first_name":"xus"}';
$objectsRaw[] = '{"id":34,"first_name":"xus"}';
$objectsRaw[] = '{"id":4,"first_name":"ABC"}';
$objectsRaw[] = '{"id":4,"first_name":"ABC"}';
# decode the json objects into PHP arrays
$objects = array_map(
function($objectJson) {
$object = json_decode($objectJson, true);
return $object;
},
$objectsRaw
);
# map the objects
$result = [];
foreach($objects as $object) {
if (array_key_exists($object['id'], $result) === false) {
$object['count'] = 1;
$result[$object['id']] = $object;
continue;
}
$result[$object['id']]['count']++;
}
# encode result
$resultRaw = array_map('json_encode', $result);
# would look like
# Array
# (
# [34] => {"id":34,"first_name":"xus","count":2}
# [4] => {"id":4,"first_name":"ABC","count":2}
# )
# reset array keys (if you need this)
$resultRaw = array_values($resultRaw);
# would look like
# Array
# (
# [0] => {"id":34,"first_name":"xus","count":2}
# [1] => {"id":4,"first_name":"ABC","count":2}
# )

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
)
)
)

How can I compare two Arrays and detect if the values are incorrect or missing?

I have to arrays I would like to compare:
$original and $duplicate.
for example here is my original file:
print_r($original);
Array ( [0] => cat423 [1] => dog456 [2] => horse872 [3] => duck082 )
and here is my duplicate:
print_r($dublicate);
Array ( [0] => cat423 [1] => dug356 )
I compare them with array_diff:
$result = array_diff($original, $dublicate);
My result:
Array ( [1] => dog456 [2] => horse872 [3] => duck082 )
So far so good, but I need to make a difference between the values which are incorrect and the values which are completely missing. Is this possible?
A way would be to crawl the entire original array, afterwards you will have two arrays, missings and duplicates.
$original = array("cat423", "dog456", "horse872", "duck082");
$duplicate = array("cat423", "dug356");
$missings = $duplicates = array();
foreach ($original as $val) {
if (in_array($val, $duplicate))
$duplicates[] = $val;
else
$missings[] = $val;
}
If you need the keys as well, you would have to alter the foreach loop like so:
foreach ($original as $key=>$val) {
if (in_array($val, $duplicate))
$duplicates[] = array("key" => $key, "value" => $val);
else
$missings[] = array("key" => $key, "value" => $val);
}
use in_array function
$original = array("cat423", "dog456", "horse872", "duck082");
$duplicate = array("cat423", "dug356");
foreach ($original as $item) {
if(in_array($item, $duplicate))
{
$dup[] = $item;
}
else
{
$miss[] = $item;
}
}
print_r($miss); #Array ( [0] => dog456 [1] => horse872 [2] => duck082 )
print_r($dup); #Array ( [0] => cat423 )
Working Preview

Don't want Array ito combine values

I Have an array in PHP that looks like:
Array ( [2099:360] => 6-3.25 [2130:361] => 4-2.5 [2099:362] => 14-8.75 )
Notice there is Two Keys that are 2099 and one that is 2130. I Have a foreach to remove the everything after the colon. the $drop is my array
$a = array();
foreach ($drop as $part=>$drop_a){
$ex_part = explode(":", $part);
$a[$ex_part[0]] = $drop_a;
}
print_r($a);
but when I print $a it displays only the recent value of the 2099?
Array ( [2099] => 14-8.75 [2130] => 4-2.5 )
Any Successions? How can I get it to display all of the values?
Thank You for Your Help
One solution is to use a multi-dimensional array to store this strategy:
$a = array();
foreach ($drop as $part=>$drop_a){
$ex_part = explode(":", $part);
if (isset($a[$ex_part[0]])) {
$a[$ex_part[0]][] = $drop_a;
} else {
$a[$ex_part[0]] = array($drop_a);
}
}
Your resulting data-set will however be different:
Array ( [2099] => Array ( [0] => 6-3.25 [1] => 14-8.75) [2130] => Array ( [0] => 4-2.5 ) )
It may be beneficial to you to preserve the second portion after the colon :
$a = array();
foreach ($drop as $part=>$drop_a){
$ex_part = explode(":", $part);
if (isset($a[$ex_part[0]])) {
$a[$ex_part[0]][$ex_part[1]] = $drop_a;
} else {
$a[$ex_part[0]] = array($ex_part[1] => $drop_a);
}
}
Now your result is a little more meaningful:
Array ( [2099] => Array ( [360] => 6-3.25 [362] => 14-8.75) [2130] => Array ( [361] => 4-2.5 ) )
Finally you can use alternative key-naming strategy if one is already occupied:
$a = array();
foreach ($drop as $part=>$drop_a){
$ex_part = explode(":", $part);
if (isset($a[$ex_part[0]])) {
$a[altName($ex_part[0], $a)] = $drop_a;
} else {
$a[$ex_part[0]] = $drop_a;
}
}
function altName($key, $array) {
$key++; // Or however you want to do an alternative naming strategy
if (isset($array[$key])) {
return altName($key, $array); // This will eventually resolve - but be careful with the recursion
}
return $key;
}
Returns:
Array
(
[2099] => 6-3.25
[2130] => 4-2.5
[2100] => 14-8.75
)
You basically have a key and a sub key for each entry, so just put them in a multidimensional array:
$a = array();
foreach ($drop as $key => $val) {
list($key, $subKey) = explode(':', $key);
$a[$key][$subKey] = $val;
}
Gives you:
Array
(
[2099] => Array
(
[360] => 6-3.25
[362] => 14-8.75
)
[2130] => Array
(
[361] => 4-2.5
)
)
You can traverse multidimensional arrays by nesting loops:
foreach ($a as $key => $subKeys) {
foreach ($subKeys as $subKey => $val) {
echo "$key contains $subKey (value of $val) <br>";
}
}

How to get the value from serialized array by using preg_match in php

I need to get the value from the serialized array by matching the index value.My unserialized array value is like
Array ( [info1] => test service [price_total1] => 10
[info2] => test servicing [price_total2] => 5 )
I need to display array like
Array ( [service_1] => Array ([info]=>test service [price_total] => 10 )
[service_2] => Array ([info]=>test servicing [price_total] => 5 ))
buy i get the result like the below one
Array ( [service_1] => Array ( [price_total] => 10 )
[service_2] => Array ( [price_total] => 5 ) )
my coding is
public function getServices($serviceinfo) {
$n = 1;
$m = 1;
$matches = array();
$services = array();
print_r($serviceinfo);
if ($serviceinfo) {
foreach ($serviceinfo as $key => $value) {
if (preg_match('/info(\d+)$/', $key, $matches)) {
print_r($match);
$artkey = 'service_' . $n;
$services[$artkey] = array();
$services[$artkey]['info'] = $serviceinfo['info' . $matches[1]];
$n++;
}
if ($value > 0 && preg_match('/price_total(\d+)$/', $key, $matches)) {
print_r($matches);
$artkey = 'service_' . $m;
$services[$artkey] = array();
$services[$artkey]['price_total'] = $serviceinfo['price_total' . $matches[1]];
$m++;
}
}
}
if (empty($services)) {
$services['service_1'] = array();
$services['service_1']['info'] = '';
$services['service_1']['price_total'] = '';
return $services;
}
return $services;
}
I try to print the matches it will give the result as
Array ( [0] => info1 [1] => 1 ) Array ( [0] => price_total1 [1] => 1 )
Array ( [0] => info2 [1] => 2 ) Array ( [0] => price_total2 [1] => 2 )
Thanks in advance.
try this. shorted version and don't use preg_match
function getServices($serviceinfo) {
$services = array();
if (is_array($serviceinfo) && !empty($serviceinfo)) {
foreach ($serviceinfo as $key => $value) {
if(strpos($key, 'info') === 0){
$services['service_'.substr($key, 4)]['info']=$value;
}elseif (strpos($key, 'price_total') === 0){
$services['service_'.substr($key, 11)]['price_total']=$value;
}
}
}
return $services;
}
$data = array('info1'=>'test service','price_total1'=>10,'info2'=>'test servicing','price_total2'=>5);
$service = getServices($data);
print_r($service);

Categories