return array containing duplicates php - php

i have a multidimensional array and i only want to keep the entries with the most duplicates. the closest i got was:
$wd = array_unique($arr);
$d = array_diff($arr, $wd);
print_r($d);
but that only works for single dimensional arrays and outputs all duplicates. how would i go about doing this?
examples of desired output:
if the array is:
array(
[1] => (
[u] => test1u
[d] => test1d
)
[2] => (
[u] => test2u
[d] => test2d
)
[3] => (
[3] => test3u
[3] => test3d
)
[1] => (
[u] => test1u
[d] => test1d
)
)
it should return array([1] => ( [u] => test1u [d] => test1d))
and if the array is:
array(
[1] => (
[u] => test1u
[d] => test1d
)
[2] => (
[u] => test2u
[d] => test2d
)
[3] => (
[3] => test3u
[3] => test3d
)
[1] => (
[u] => test1u
[d] => test1d
)
[2] => (
[u] => test2u
[d] => test2d
)
)
it should return array([1] => ( [u] => test1u [d] => test1d)[2] => ( [u] => test2u [d] => test2d))
but if the array is:
array(
[1] => (
[u] => test1u
[d] => test1d
)
[2] => (
[u] => test2u
[d] => test2d
)
[3] => (
[3] => test3u
[3] => test3d
)
[1] => (
[u] => test1u
[d] => test1d
)
[2] => (
[u] => test2u
[d] => test2d
)
[1] => (
[u] => test1u
[d] => test1d
)
)
it should only return array([1] => ( [u] => test1u [d] => test1d))
EDIT:
there are duplicate entries in the array because the array came from $arr = json_decode($arr); and the original JSON had duplicate entries.
if there is a better way to do this without decoding the json, let me know.
this is being used as part of a search program. the JSON is an array of all of the entries from the source array that met the criteria for one of the search terms. keeping the entries with the most duplicates insures that those entries contained most if not all of the search terms.
here is the JSON file being decoded:
[{"1":[{"u":"testing","d":"2017\/04\/27","st":"Test","i":"roses","v":"1","t":"org","sp":"N\/A","k":"0","img":"--"}]},{"2":[{"u":"testing","d":"2017\/04\/27","st":"Test","i":"roses","v":"1","t":"org","sp":"N\/A","k":"0","img":"--"}]},{"5":[{"u":"testing","d":"2017\/04\/27","st":"Test","i":"roses daffodil","v":"1","t":"org","sp":"N\/A","k":"0","img":"--"}]},{"3":[{"u":"testing","d":"2017\/04\/27","st":"Test","i":"daffodil","v":"1","t":"org","sp":"N\/A","k":"0","img":"--"}]},{"4":[{"u":"testing","d":"2017\/04\/27","st":"Test","i":"daffodil","v":"1","t":"org","sp":"N\/A","k":"0","img":"--"}]},{"5":[{"u":"testing","d":"2017\/04\/27","st":"Test","i":"roses daffodil","v":"1","t":"org","sp":"N\/A","k":"0","img":"--"}]},{"6":[{"u":"testing","d":"2017\/04\/27","st":"Test","i":"roses daffodil","v":"1","t":"org","sp":"N\/A","k":"0","img":"--"}]}]
in this case the search that made this JSON was for "roses daffodil"

the second example it add – each index just can appear once.
for the first this should work fine:
<?php
$array[] = array( 'u' => 'test1u', 'd' => 'test1d' );
$array[] = array( 'u' => 'test2u', 'd' => 'test2d' );
$array[] = array( '3' => 'test3u', '3' => 'test3d' );
$array[] = array( 'u' => 'test1u', 'd' => 'test1d' );
$array[] = array( 'u' => 'test2u', 'd' => 'test2d' );
var_export( $array );
//echo("\n" . array_count_values($array) . "\n");
foreach( $array as $k => $v ){
foreach( $array as $ke => $ve ){
if( $k == $ke )
continue;
if( $v == $ve ) {
$d[$k]=$v;
unset($array[$k]);
}
}
}
var_export( $d );
?>
unfortunately array_count_values only works for String and int, so it does not work when you have complex values.

First you array cannot have same key. Check the live demo.
<?php
$array[] = array( 'u' => 'test1u', 'd' => 'test1d' );
$array[] = array( 'u' => 'test2u', 'd' => 'test2d' );
$array[] = array( 'u' => 'test3u', 'd' => 'test3d' );
$array[] = array( 'u' => 'test1u', 'd' => 'test1d' );
$array[] = array( 'u' => 'test2u', 'd' => 'test2d' );
$array = array_map(function($v){return implode('-', $v);}, $array);
$count = array_count_values($array);
print_r($count);
arsort($count);
$max = current($count);
while(current($count) == $max)
{
$arr = explode('-', key($count));
$result[] = array('u' => $arr[0], 'd' => $arr[1]);
next($count);
}
print_r($result);

i have found the solution! bit long winded but it works!
$json = json_decode($json);
$jsonoutc = $jsonout = "";
$arrid = $arrout = $disp = array();
foreach ($json as $null => $arr){
foreach ($arr as $key => $null){
$arrid[] = $key;
}
}
$vals = array_count_values($arrid);
foreach ($vals as $val => $counted){
if ($counted > $jsonoutc){
$jsonoutc = $counted;
}
}
foreach ($vals as $val => $counted){
if ($counted == $jsonoutc){
$arrout[] = $val;
}
}
foreach ($arrout as $null => $val){
foreach ($json as $null => $arr){
foreach ($arr as $key => $list){
if ($key == $val){
$disp[$key] = $list;
}
}
}
}
print_r($disp);

Related

Grouping in array

I have following array..I am trying to group this.
Array
(
[0] => Array
(
[Title] => HoMedics MAN-300
[ean] => 31262006288
[upc] => 31262006288
[ProductImageName] =>
[CdnUri] =>
[ASIN] => B000050FEU
[ListPrice] => 129.99
[Status] => 2
[ActualPrice] => 129.99
[ProductID] => 5286728
)
)
I want to group this into
Array
(
[0] => Array
(
[VitalInfo]=>array(
[Title] => HoMedics MAN-300
[ean] => 31262006288
[upc] => 31262006288
[ProductImageName] =>
[CdnUri] =>
[ASIN] => B000050FEU
)
[Price]=>array(
[ListPrice] => 129.99
[Status] => 2
[ActualPrice] => 129.99
[ProductID] => 5286728
)
)
I tried but it doesn't happen as I want ...any help would be great...Thanx in advance..
try this,
CODE :
foreach($old_array as $key_old => $val_old)
{
foreach($val_old as $key => $val)
{
if(in_array($key, $VitalInfo_array))
{
$new_array[$key_old]['VitalInfo'][$key] = $val;
}
else
{
$new_array[$key_old]['Price'][$key] = $val;
}
}
}
OUTPUT :
Array
(
[0] => Array
(
[VitalInfo] => Array
(
[Title] => HoMedics MAN-300
[ean] => 31262006288
[upc] => 31262006288
[ProductImageName] =>
[CdnUri] =>
[ASIN] => B000050FEU
)
[Price] => Array
(
[ListPrice] => 129.99
[Status] => 2
[ActualPrice] => 129.99
[ProductID] => 5286728
)
)
)
DEMO
i hope it will be helpful.
Simply loop through your array and customize a new array accordingly.
Assuming $array is the original array, and $result is the customized array, try this:
foreach ($array as $k => $arr) {
$result[$k]['VitalInfo'] = array(
'Title' => $arr['Title'],
'ean' => $arr['ean'],
'upc' => $arr['upc'],
'ProductImageName' => $arr['ProductImageName'],
'CdnUri' => $arr['CdnUri'],
'ASIN' => $arr['ASIN']
);
$result[$k]['Price'] = array(
'ListPrice' => $arr['ListPrice'],
'Status' => $arr['Status'],
'ActualPrice' => $arr['ActualPrice'],
'ProductID' => $arr['ProductID']
);
}
Input : $info // Your Original Array
Ouput : $finalArr // Your Required Array
$vitalInfo = array ('Title','ean','upc','ProductImageName','CdnUri','ASIN');
$price = array ('ListPrice','Status','ActualPrice','ProductId');
$finalArr = array();
foreach ($info as $arr) {
$result = array();
foreach($arr as $k => $v){
if(in_array($k,$vitalInfo))
$result['VitalInfo'][$k] = $v;
else if(in_array($k,$price))
$result['Price'][$k] = $v;
}
$finalArr[] = $result;
}
If you are grouping this in php, have a look at these answers.
Or just copy this:
$input = [0 => [
'Title' => 'HoMedics MAN-300',
'ean' => 31262006288,
'upc' => 31262006288,
'ProductImageName' => '',
'CdnUri' => '',
'ASIN' => 'B000050FEU',
'ListPrice' => 129.99,
'Status' => 2,
'ActualPrice' => 129.99,
'ProductID' => 5286728
]];
foreach ($input as $in){
$out['VitalInfo'] = [];
$out['Price'] = [];
foreach ($in as $key => $i){
if (in_array($key, ['Title', 'ean', 'upc', 'ProductImageName', 'CdnUri', 'Asin'])){
$out['VitalInfo'][] = [$key => $i];
} else {
$out['Price'][] = [$key => $i];
}
}
$output[]=$out;
}
echo '<pre>';
var_dump($output);

Remove key value from array in php

This is my db result,
Array ([0] => Array ( [shopname] => Shop name [fueltype] => Pertol [amount] => 1000 )
[1] => Array ( [shopname] => dfsdfsd [fueltype] => Pertol [amount] => 54456 )
[2] => Array ( [shopname] => dfsdfsd [fueltype] => Disel [amount] => 54456 )
)
I need result like
[["Shop name", "Pertol", 1000],["dfsdfsd", "Pertol", 54456],["Shop name", "Disel", 54456]]
How to get like this, I have no idea?
array_map() along with array_values() will work for you:-
<?php
$array = Array ( '0' => Array ( 'shopname' => 'Shop name','fueltype' => 'Pertol','amount' => 1000 ),
'1' => Array ( 'shopname' => 'dfsdfsd' ,'fueltype' => 'Pertol','amount' => 54456 ),
'2' => Array ( 'shopname' => 'dfsdfsd','fueltype' => 'Disel','amount' => 54456 )
);
$values_data_only = array_map('array_values', $array);
$desire_result = json_encode($values_data_only);
echo $desire_result;
?>
Output:- https://eval.in/395344
Also via simple foreach() it is possible:-
<?php
$array = Array ( '0' => Array ( 'shopname' => 'Shop name','fueltype' => 'Pertol','amount' => 1000 ),
'1' => Array ( 'shopname' => 'dfsdfsd' ,'fueltype' => 'Pertol','amount' => 54456 ),
'2' => Array ( 'shopname' => 'dfsdfsd','fueltype' => 'Disel','amount' => 54456 )
);
$new_array = array();
foreach ($array as $k=> $arr){
$new_array[$k][] = $arr['shopname'];
$new_array[$k][] = $arr['fueltype'];
$new_array[$k][] = $arr['amount'];
}
echo "<pre/>";print_r($new_array);
$desired_result_2 = json_encode($new_array);
echo $desired_result_2;
?>
Output:-https://eval.in/395354
$mapped = array_map('array_values', $input_array); // apply filter so we dont get the keys
$json = json_encode($mapped);
Just try with:
$input = array( /* your input data */ );
$output = array();
foreach ($input as $data) {
$output[] = array_values($data);
}

merge arrays where some value of parent arrays is not equals

I array of arrays, what look something like that:
$messages = array (
0 =>
array(
'keyT' => 'id.key'
'mess' => array(
array(1,0)
)
...
)
I want to merge mess preperties of arrays where 'keyT' is not equals.
I run trought the arrays:
foreach ($messages as $k => $current) {
foreach ($messages as $ke => $all) {
if ($current['keyT'] == $all['keyT']) {
array_merge( ... )
}
}
}
But this not deve me any results. Maybe somebody can help me. Thanks!
Try this code
$messages = array(
0 =>
array(
'keyT' => 'A',
'mess' => array(
array(1, 0)
)
),
1 =>
array(
'keyT' => 'A',
'mess' => array(
array(1, 2)
)
),
2 =>
array(
'keyT' => 'B',
'mess' => array(
array(3, 4)
)
)
);
$result = array();
foreach ($messages as $msg) {
$key = $msg['keyT'];
if (!isset($result[$key])) {
$result[$key] = array();
}
$result[$key] = array_merge($result[$key], $msg['mess']);
}
print_r($result);
Output
Array
(
[A] => Array
(
[0] => Array
(
[0] => 1
[1] => 0
)
[1] => Array
(
[0] => 1
[1] => 2
)
)
[B] => Array
(
[0] => Array
(
[0] => 3
[1] => 4
)
)
)

Multidimensional Array Find and Update The Value using PHP

I can't get suitable title for this thread (help me). I can't describe this problem so here the example of my problem.
My array :
Array ( [0] => Array ( [answer] => a [score] => 3 )
[1] => Array ([answer] => b [score] => 4 )
[2] => Array ( [answer] => h [score] => 3)
[3] => Array ( [answer] => a [score] => 4 ))
...
And I wanna get an output like this :
Array ( [0] => Array ( [answer] => a [score] => 7 )
[1] => Array ([answer] => b [score] => 4 )
[2] => Array ( [answer] => h [score] => 3))
...
You can see a change of score subkey in index key 0. This is happen because there is two value 'a' in answer subkey from index key 0 and 3. The score changed to 7 because of the sum of both (3+4). Really I don't have an idea for this, sorry for my english and thanks for help.
Feel free to comment. :)
$merged = array();
foreach ($array as $answer) {
if (isset($merged[$answer['answer']])) {
$merged[$answer['answer']]['score'] += $answer['score'];
} else {
$merged[$answer['answer']] = $answer;
}
}
var_dump($merged);
Check this answer, not using loop :
$arr = array ( array ( 'answer' => 'a', 'score' => 3 ),
array ( 'answer' => 'b', 'score' => 4 ),
array ( 'answer' => 'h', 'score' => 3),
array ( 'answer' => 'a', 'score' => 4 ));
$t = array_reduce($arr, function($result, $item) {
if(array_key_exists($item['answer'],$result)){
$result[$item['answer']] = array('answer' => $item['answer'], 'score' => $item['score']+$result[$item['answer']]['score']);
}
else{
$result[$item['answer']] = array('answer' => $item['answer'], 'score' => $item['score']);
}
return $result;
},array());
echo "<pre>";
print_r($t);
Output :
Array
(
[a] => Array
(
[answer] => a
[score] => 7
)
[b] => Array
(
[answer] => b
[score] => 4
)
[h] => Array
(
[answer] => h
[score] => 3
)
)
I though of using a temporary array:
/* Current array */
$array = array(
array("answer" => "a", "score" => 3),
array("answer" => "b", "score" => 4),
array("answer" => "h", "score" => 3),
array("answer" => "a", "score" => 4)
);
/* Using a temporary array */
$tmp_array = array();
foreach($array as $subarray){
if(array_key_exists($subarray["answer"], $tmp_array)){
$tmp_array[$subarray["answer"]] += $subarray["score"];
}else{
$tmp_array[$subarray["answer"]] = $subarray["score"];
}
}
/* Creating a new formatted array */
$new_array = array();
foreach($tmp_array as $key => $value){
$new_array[] = array("answer" => $key, "score" => $value);
}
print_r($new_array);

array transformation in php

how would you turn this array:
Array
(
[0] => 234234234
[1] => 657567567
[2] => 234234234
[3] => 5674332
)
into this:
Array
(
[contacts] => Array(
[0] => Array
(
[number] => 234234234
[contact_status] => 2
[user_id] =>3
)
[1] => Array
(
[number] => 657567567
[contact_status] => 2
[user_id] =>3
)
[3] => Array
(
[number] => 234234234
[contact_status] => 2
[user_id] =>3
)
[4] => Array
(
[number] => 5674332
[contact_status] => 2
[user_id] =>3
)
)
)
is there a cakephp specific way how to transform this array?
thank you
nicer
$contact_status = 2;
$user_id = 1;
foreach($input as $number)
$output['contacts'][] = compact('number', 'contact_status', 'user_id');
Try this:
$output = array('contacts'=>array());
foreach ($input as $val) {
$output['contacts'][] = array(
'number' => $val,
'contact_status' => 2,
'user_id' => 3
);
}
I assume that contact_status and user_id are static since you didn’t tell anything else.
$input = array(...);
$arr = array();
foreach ($input as $id) {
$arr[] = array(
'number' => $id,
'contact_status' => 2,
'userid' => 3;
);
}
$output = array('contacts' => $arr);
A little bit of cleanup from sterofrog's solution. Declare the array and use array_push instead of assigning it to an empty index.
$output = array( );
$contact_stats = 2;
$user_id = 3;
foreach( $input as $number ) {
array_push( $output[ 'contact' ], compact(
'number',
'contact_status',
'user_id'
));
}
You can simply use the array_map function like this:
$result = array_map(function ($n){
return array(
'number' => $n,
'contact_status' => 2,
'user_id' => 3);
}, $original);

Categories