remove duplicate items from object php - 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}
# )

Related

Count duplicates in treemap

I'm trying to build a tree-map from categories. I have the categories (I have a lot of categories and I want to remove duplicates and show them in a tree-map view with count) and I have the following code:
<?php
$cat = array(
"Sneakers/Men",
"Sneakers/Women",
"Accessories/Jewellery/Men",
"Accessories/Jewellery/Men",
"Accessories/Jewellery/Women",
"Accessories/Jewellery/Men/Bvlgari"
);
$out = [];
foreach ($cat as $str) {
$lookup = &$out;
$parts = explode("/", $str);
foreach ($parts as $part) {
$lookup = &$lookup[$part];
if (!isset($lookup))
$lookup = [];
if ($part == end($parts))
$lookup = is_array($lookup) ? 1 : ++$lookup;
}
}
print_r($out);
OUTPUT:
Array
(
[Sneakers] => Array
(
[Men] => 1
[Women] => 1
)
[Accessories] => Array
(
[Jewellery] => Array
(
[Men] => 3
[Women] => 1
)
)
)
I would like to be:
Array
(
[Sneakers] => Array
(
[Men] => 1
[Women] => 1
)
[Accessories] => Array
(
[Jewellery] => Array
(
[Men] => Array (
[Bvlgari] => 1
)
[Women] => 1
)
)
)
You're losing information with both of those formats and the suggested answer is not going to cut it. You do need recursion and each item needs to hold a count and children.
$cat_paths = [
'Sneakers/Men',
...
];
$cat_counts = $item = [# template of each item
'count' => 0,
'children' => [],
];
foreach ($cat_paths as $cat_path) {
$level = &$cat_counts;# use a reference for recursion
if ($cat_path) {# allow uncategorized to be in root of tree
$cat_path = explode('/', $cat_path);
do {
$cat = array_shift($cat_path);
if (!isset($level['children'][$cat])) {
$level['children'][$cat] = $item;
}
$level = &$level['children'][$cat];# step down into tree
} while ($cat_path);
}
$level['count']++;
}
unset($level);

Update Multidimentional Array with another Array for existing Keys PHP

I have two arrays:
('admin','admin2', 'admin3' can be too many, and names can also differ other than 'admin')
$old = array(
array('admin'=>array('a'=>'aaa','b'=>'bbb')),
array('admin2'=>array('c'=>'ccc','d'=>'ddd'))
);
$new = array(
array('admin2'=>array('e'=>'eee','f'=>'fff')),
array('admin3'=>array('g'=>'ggg','h'=>'hhh'))
);
I want to have this array from both above arrays:
(new array with all different keys in both PLUS similar keys from new array)
$output = array(
array('admin'=>array('a'=>'aaa','b'=>'bbb')),
array('admin2'=>array('e'=>'eee','f'=>'fff')),
array('admin3'=>array('g'=>'ggg','h'=>'hhh'))
);
// Remove one level of array to make arrays as ['admin'=>array, 'admin2'=>array]
$old1 = call_user_func_array('array_merge', $old);
$new1 = call_user_func_array('array_merge', $new);
// Make replacement
$ready = array_replace($old1, $new1);
// Return level making every item as array
$result = array();
foreach($ready as $k=>&$v)
$result[] = array($k=>$v);
print_r($result);
demolink
This code will solve your problem :
<?php
$array1 = array(
array('admin'=>array('a'=>'aaa','b'=>'bbb')),
array('admin2'=>array('c'=>'ccc','d'=>'ddd'))
);
$array2 = array(
array('admin2'=>array('e'=>'eee','f'=>'fff')),
array('admin3'=>array('g'=>'ggg','h'=>'hhh'))
);
$output = $array1; ///merge array1 into output array
foreach($array2 as $key => $val)
{
$is_present_key = false;
$first_key = key($val);
foreach($output as $k => $v)
{
if(array_key_exists($first_key,$output[$k])) ////check if key exit in $output array
{
$output[$k] = $val; ///push new value if key exists in $output
$is_present_key = true;
}
}
if($is_present_key == false)///skip for duplicate of new values if key exists in $output
{
$output[] = $val;
}
}
echo "<pre>"; print_r($output);
?>
This will give you :
Array
(
[0] => Array
(
[admin] => Array
(
[a] => aaa
[b] => bbb
)
)
[1] => Array
(
[admin2] => Array
(
[e] => eee
[f] => fff
)
)
[2] => Array
(
[admin3] => Array
(
[g] => ggg
[h] => hhh
)
)
)
LIVE EXAMPLE
$old = array(
array('admin'=>array('a'=>'aaa','b'=>'bbb')),
array('admin2'=>array('c'=>'ccc','d'=>'ddd'))
);
$new = array(
array('admin2'=>array('e'=>'eee','f'=>'fff')),
array('admin3'=>array('g'=>'ggg','h'=>'hhh'))
);
$arr=array_merge($new,$old);
$new_arr=array();
foreach($arr as $key=>$val){
foreach($val as $k=>$v){
if(array_key_exists($k, $new_arr)){
continue;
}else{
$new_arr[$k]=$v;
}
}
}
echo "<pre>";print_r($new_arr); echo "</pre>";

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

Create multidimensional array from rows

The result of a query in my database returns something like this (a record for each row):
1.
1.1.
1.1.01.
1.1.01.001
1.2.
1.2.01.
1.2.02.
I'm trying to create something that returns me a multidimensional array in a tree format, like this:
array(
'1.' => array(
'1.1' => array(
'1.1.01.' => array(
(int) 0 => '1.1.01.001'
)
),
'1.2' => array(
(int) 0 => '1.2.01.',
(int) 1 => '1.2.02.'
)
)
)
All I could think to do was reverse the order of elements using explode().
I appreciate any suggestions.
Your format is very tricky because of :
1.2.
1.2.01. |
1.2.02. V Making this array instead of value
You can try
$string = "1.
1.1.
1.1.01.
1.1.01.001
1.2.
1.2.01.
1.2.02.";
$array = explode("\n", $string);
$data = array();
$temp = &$data;
$it = new CachingIterator(new ArrayIterator($array), CachingIterator::FULL_CACHE);
$continue = false;
foreach ( $it as $v ) {
$v = trim($v);
if ($it->hasNext()) {
$next = trim($it->getInnerIterator()->current());
if (stripos($next, $v) === 0) {
$temp = &$temp[$v];
} else {
$temp[] = $v;
if (strlen($next) != strlen($v)) {
$temp = &$data;
}
}
} else {
$temp[] = $v;
}
}
print_r($data);
Output
Array
(
[1.] => Array
(
[1.1.] => Array
(
[1.1.01.] => Array
(
[0] => 1.1.01.001
)
)
)
[1.2.] => Array
(
[0] => 1.2.01.
[1] => 1.2.02.
)
)
Here is a move COMPLEX demo

How do i split this array into two?

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;
}
}
}

Categories