Select arrays with multiple occurence from a array of arrys - PHP - php

My array is given below. Which contains more than one arrays.
Array
(
[0] => Array
(
[user_id] => 1
[name] => name1
)
[1] => Array
(
[user_id] => 2
[name] => name2
)
[2] => Array
(
[user_id] => 2
[name] => name2
)
[3] => Array
(
[user_id] => 3
[name] => name3
)
)<br/>
I need arrays which has more than one occurence.In this case
Array
(
[user_id] => 2
[name] => name2
)

Try this.
function get_multi_occur($my_array)
{
foreach ($my_array as $id => $a) {
$key = $a[user_id] . $a[name];
if ($s[$key]['cnt'] == 0) {
$s[$key]['cnt'] = 1;
$s[$key]['id'] = $id;
} else {
$s[$key]['cnt']++;
}
}
foreach ($s as $r) {
if ($r['cnt'] >= 2) {
$ret[] = $my_array[$r[id]];
}
}
return $ret;
}

foreach ($array as $key_1=>$sub_array_1)
{
foreach ($array as $key_2=>$sub_array_2)
{
if ($sub_array_1 == $sub_array_2 &&
$key_1 != $key_2)//prevent to compare same sub arrays
print_r($sub_array_1);
}
}
something like this

You can try
$array = Array(
"0" => Array("user_id" => 1,"name" => "name1"),
"1" => Array("user_id" => 2,"name" => "name2"),
"2" => Array("user_id" => 2,"name" => "name2"),
"3" => Array("user_id" => 3,"name" => "name3"));
$d = $s = array();
array_map(function ($v) use(&$d, &$s) {
array_key_exists($v['user_id'], $s) && ! array_key_exists($v['user_id'], $d) ? $d[$v['user_id']] = $v : $s[$v['user_id']] = $v;
}, $array);
var_dump($d);
Output
array
2 =>
array
'user_id' => int 2
'name' => string 'name2' (length=5)

Create a new array that will store data that have same values.
Try this code :
$array_existing = array();
$ctr = 0;
foreach ($first_array as $key => $first) :
foreach ($second_array as $keytwo => $second) :
if ($first['user_id'] == $second['user_id'] && $first['name'] == $second['name']) {
$array_existing[$ctr]['user_id'] = $first['user_id'];
$array_existing[$ctr]['name'] = $first['name'];
$array_existing[$ctr]['first_index'] = $key;
$array_existing[$ctr]['second_index'] = $keytwo;
$ctr++;
}
endforeach;
endforeach;
var_dump($array_existing);

Related

php remove empty 'columns' in multidimensional, associative array

Goal: Generate an array that includes only those 'columns' with data, even though a 'header' may exist.
Example Data:
Array (
[HeaderRow] => Array (
[0] => Employee [1] => LaborHours [2] => 0.1 [3] => 0.25 [4] => 0.5 [5] => 0.8
)
[r0] => Array (
[0] => Joe [1] => 5 [2] => [3] => [4] => 50 [5] =>
)
[r1] => Array (
[0] => Fred [1] => 5 [2] => 10 [3] => [4] => [5] =>
)
)
Desired Output:
Array (
[HeaderRow] => Array (
[0] => Employee [1] => LaborHours [2] => 0.1 [4] => 0.5
)
[r0] => Array (
[0] => Joe [1] => 5 [2] => [4] => 50
)
[r1] => Array (
[0] => Fred [1] => 5 [2] => 10 [4] =>
)
)
So, in this very dumbed down example, the HeaderRow will always have data, but if both c0 and c1 are empty (as is the case for [3] and [5]) then I want to remove. I tried iterating through with for loops like I would in other languages, but that apparently doesn't work with associative arrays. I then tried doing a transpose followed by two foreach loops, but that failed me as well. Here's a sample of my for loop attempt:
Attempt with For Loop
for ($j = 0; $j <= count(reset($array))-1; $j++) {
$empty = true;
for ($i = 1; $i <= count($array)-1; $i++) {
if(!empty($array[$i][$j])) {
$empty = false;
break;
}
}
if ($empty === true)
{
for ($i = 0; $i <= count($array); $i++) {
unset($array[$i][$j]);
}
}
}
return $array;
Attempt with transpose:
$array = transpose($array);
foreach ($array as $row)
{
$empty = true;
foreach ($row as $value)
{
if (!empty($value))
{
$empty = false;
}
}
if ($empty) {
unset($array[$row]);
}
}
$array = transpose($array);
return $array;
function transpose($arr) {
$out = array();
foreach ($arr as $key => $subarr) {
foreach ($subarr as $subkey => $subvalue) {
$out[$subkey][$key] = $subvalue;
}
}
return $out;
}
I know the transpose one isn't terribly fleshed out, but I wanted to demonstrate the attempt.
Thanks for any insight.
We can make this more simpler. Just get all column values using array_column.
Use array_filter with a custom callback to remove all empty string values.
If after filtering, size of array is 0, then that key needs to be unset from all
subarrays.
Note: The arrow syntax in the callback is introduced since PHP 7.4.
Snippet:
<?php
$data = array (
'HeaderRow' => Array (
'0' => 'Employee','1' => 'LaborHours', '2' => 0.1, '3' => 0.25, '4' => 0.5, '5' => 0.8
),
'r0' => Array (
'0' => 'Joe', '1' => 5, '2' => '','3' => '', '4' => 50, '5' => ''
),
'r1' => Array (
'0' => 'Fred', '1' => 5,'2' => 10, '3' => '', '4' => '', '5' => ''
)
);
$cleanup_keys = [];
foreach(array_keys($data['HeaderRow']) as $column_key){
$column_values = array_column($data, $column_key);
array_shift($column_values); // removing header row value
$column_values = array_filter($column_values,fn($val) => strlen($val) != 0);
if(count($column_values) == 0) $cleanup_keys[] = $column_key;
}
foreach($data as &$row){
foreach($cleanup_keys as $ck){
unset($row[ $ck ]);
}
}
print_r($data);
It figures, I work on this for a day and have a moment of clarity right after posting. The answer was that I wasn't leveraging the Keys.:
function array_cleanup($array)
{
$array = transpose($array);
foreach ($array as $key => $value)
{
$empty = true;
foreach ($value as $subkey => $subvalue)
{
if ($subkey != "HeaderRow") {
if (!empty($subvalue))
{
$empty = false;
}
}
}
if ($empty) {
unset($array[$key]);
}
}
$array = transpose($array);
return $array;
}

how to get array with unique values in laravel/php

I need to merge arrays into 1 array but what I need is to remove before the main data they b oth have in common (duplicated values i mean), I need only unique values when merged.
array formed from foreach.
public $arrayfields= [];
public $itemMap = [];
public function getRowMapping(array $row,$uniqueField,$moduleName)
{
$arrayData = [];
foreach ($this->columnMapping as $key => $value) {
$row = $this->moduleType($key,$value,$row,$moduleName);
}
$unique = $row[$uniqueField];
if(!isset($this->itemMap[$unique])){
$this->itemMap[$unique] = $row;
$this->itemMap[$unique][$unique]['items'] = [];
}
$this->itemMap[$unique]['items'][] = $row['items'];
return $row;
}
i changed little bit to my input
How can i do that?
so now the input will be like this
Array
(
[bill_type] => 1
[bill_number] => BIL-003
[order_number] => ON-003
[items] => Array
(
[track_inventory] => 0
[sku1] => sku1
[name] => Kidswear1
)
)
Array
(
[bill_type] => 1
[bill_number] => BIL-003
[order_number] => ON-003
[items] => Array
(
[track_inventory] => 0
[sku1] => sku2
[name] => Pant
)
)
Array
(
[bill_type] => 1
[bill_number] => BIL-002
[order_number] => ON-002
[items] => Array
(
[track_inventory] => 0
[sku1] => sku3
[name] => Pants
)
)
The final output I'm looking for is
Array
(
[BIL-003] => Array
(
[bill_type] => 1
[order_number] => ON-003
[items] => Array
(
[0] => Array(
[track_inventory] => 0
[sku1] => sku1
[name] => Kidswear1
)
[1] => Array
(
[track_inventory] => 0
[sku1] => sku2
[name] => Pant
)
)
[BIL-002] => Array
(
[bill_type] => 1
[order_number] => ON-002
[items] => Array
(
[0] => Array(
[track_inventory] => 0
[sku1] => sku3
[name] => pants
)
)
)~~~
I think there is no standard library function to accomplish this.
So here is the function that accomplishes this:
function merge($array1, $array2)
{
$arraymerged = [];
if (is_array($array1) && is_array($array2)) {
//collect the keys of two arrays
$keys = [];
foreach ($array1 as $key => $value) {
$keys[$key] = true;
}
foreach ($array2 as $key => $value) {
$keys[$key] = true;
}
//merge key values for each key
foreach ($keys as $key => $value) {
if (isset($array1[$key]) && isset($array2[$key])) {
if ($array1[$key] == $array2[$key]) {
$arraymerged[$key] = $array1[$key];
} else {
$arraymerged[$key] = [$array1[$key], $array2[$key]];
}
} else if (isset($array1[$key]))
$arraymerged[$key] = $array1[$key];
else
$arraymerged[$key] = $array2[$key];
}
return $arraymerged;
}
}
Here is my suggestion,
if the input is array, check my answer on this post Convert an associative array into an associative array which has a key with another associative array as its value in php
otherwise check below code.
bill_number as unique key and run foreach and append items array elements.
let me give you an example
$arr1 = [
"bill_type" => 1,
"bill_number" => 'BIL-003',
"items"=>[
0 => [
"name"=>"test"
]
]
];
$arr2 = [
"bill_type" => 1,
"bill_number" => 'BIL-003',
"items"=>[
0 => [
"name"=>"test_2"
]
]
];
$formattedArr = [];
//merge these arrays
$combinedArr = [];
$combinedArr[] = $arr1;
$combinedArr[] = $arr2;
foreach($combinedArr as $key=>$value){
$formattedArr[$value['bill_number']]["bill_type"] = $value["bill_type"];
$formattedArr[$value['bill_number']]["items"][] = $value["items"];
}
print_r($formattedArr);
I haven't tested this code, but i think this will be ans to your question.
<?php
$a1 = array(
"bill_type" => "1",
"bill_number" => "BIL-003",
"order_number" => "ON-003",
"items" => array(
"track_inventory" => "0",
"sku1" => "sku1",
"name" => "Kidswear1"
)
);
$a2 = array(
"bill_type" => "1",
"bill_number" => "BIL-003",
"order_number" => "ON-003",
"items" => array(
"track_inventory" => "0",
"sku1" => "sku2",
"name" => "Pant"
)
);
$result = function ($a1, $a2) {
$b1 = $a1['items'];
$b2 = $a2['items'];
$c1 = $a1;
$c2 = $a2;
unset($c1['items']);
unset($c2['items']);
if (count(array_diff($c1, $c2)) == 0) {
if (count(array_diff($b1, $b2)) != 0) {
$c1['items'] = [$b1, $b2];
} else {
$c1['items'] = $b1;
}
return $c1;
}else{
//you should complete this part by yourself, if first parts are not equal.
}
return $c1;
};
$r = $result($a1, $a2);
var_dump($r);
result:
(array) [4 elements]
bill_type: (string) "1"
bill_number: (string) "BIL-003"
order_number: (string) "ON-003"
items:
(array) [2 elements]
0:
(array) [3 elements]
track_inventory: (string) "0"
sku1: (string) "sku1"
name: (string) "Kidswear1"
1:
(array) [3 elements]
track_inventory: (string) "0"
sku1: (string) "sku2"
name: (string) "Pant"

Simplify Array Duplicate Element in Array PHP

How can we find the count of duplicate elements in a multidimensional array,
I have an array like this:
Array
(
[0] => Array
(
[brti] => 29
)
[1] => Array
(
[voda] => 6
)
[2] => Array
(
[btel] => 8
)
[3] => Array
(
[btel] => 10
)
)
Question: How to simplify the structure of array, i mean can be counting the value if there is indicate that have same key ?
just like this:
Array
(
[0] => Array
(
[brti] => 29
)
[1] => Array
(
[voda] => 6
)
[2] => Array
(
[btel] => 18
)
)
So far, i've tried this way, but it didn't help me. My array is store in $test
$test = [sample array]
$count = array();
foreach ($test as $key => $value) {
foreach ($value as $k => $val) {
if (isset($count[$val])) {
++$count[$val];
} else {
$count[$value] = 1;
}
}
}
print_r($count);
<?php
$array = [
"0" => ["brti" => 29],
"1" => ["voda" => 6],
"2" => ["btel" => 8],
"3" => ["btel" => 10],
];
$final = array();
array_walk_recursive($array, function($item, $key) use (&$final){
$final[$key] = isset($final[$key]) ? $item + $final[$key] : $item;
});
print_r($final);
});
check demo
You can do it in very simple way,
$test = [];
foreach ($array as $value)
{
foreach ($value as $k => $v)
{
// $test[$k] = ($test[$k] ?? 0); // initialised if not php 7+
$test[$k] = (empty($test[$k]) ? 0: $test[$k]); // below php 7
$test[$k] += $v;
}
}
print_r($test);
Output:
Array
(
[brti] => 29
[voda] => 6
[btel] => 18
)
Working demo.

How to merge two array in according to value in PHP?

I have two array and I need to merge it together !!
Array 1
Array
(
[0] => Array
(
[brand] => CARTIER
[amount_2014] => 136476
)
[1] => Array
(
[brand] => TIFFANY & CO.
[amount_2014] => 22000
)
[2] => Array
(
[brand] => Test
[amount_2014] => 33000
)
)
Array 2
Array
(
[0] => Array
(
[brand] => CARTIER
[amount_2013] => 22052
)
[1] => Array
(
[brand] => Test
[amount_2013] => 3313
)
)
I need the result array as:
Array
(
[0] => Array
(
[brand] => CARTIER
[amount_2014] => 136476
[amount_2013] => 22052
)
[1] => Array
(
[brand] => TIFFANY & CO.
[amount_2014] => 22000
[amount_2013] => 0
)
[2] => Array
(
[brand] => Test
[amount_2014] => 33000
[amount_2013] => 3313
)
)
So for every [brand] I need the amount in [amount_2014] & [amount_2013], if any one is not present then I need it value as 0;
I am using CodeIgniter for this project, I have only one table with field (brand, amount, year) am issuing two queries for getting sum of amount for 2013 & 2014.
(I am fighting with array_merge and array_combine but no use for me in this case, if any one can help with query then it's also very much helpful).
Try this:
function cars_array_merge()
{
$arrays = func_get_args();
foreach ($arrays as &$array)
{
$new_arr = array();
foreach ($array as $value)
{
$brand = $value['brand'];
unset($value['brand']);
$new_arr[$brand] = $value;
}
$array = $new_arr;
}
$arrays = call_user_func_array('array_merge_recursive', $arrays);
foreach ($arrays as $brand => &$array)
$array['brand'] = $brand;
return array_values($arrays);
}
// testing
$arr1 = [
[ 'brand' => 'CARTIER', 'mount_2014' => 136476 ],
[ 'brand' => 'TIFFANY & CO.', 'mount_2014' => 22000 ]
];
$arr2 = [
[ 'brand' => 'CARTIER', 'mount_2013' => 22052 ]
];
print_r(cars_array_merge($arr1, $arr2));
Output:
Array
(
[0] => Array
(
[mount_2014] => 136476
[mount_2013] => 22052
[brand] => CARTIER
)
[1] => Array
(
[mount_2014] => 22000
[brand] => TIFFANY & CO.
)
)
<?php
for ($i = 0, $max = count($arr1); $i < $max; ++$i) {
$arr1[$i]['amount_2013'] = isset($arr2[$i]['amount_2013']) ? $arr2[$i]['amount_2013'] : 0;
}
$merge = array_merge($arr1, $arr2);
$temp = $merge;
$newArr = array(); $key_array = array();
foreach($merge as $key=>$val){
$b = $val['brand'];
$a1 = isset($val['amount_2013']) ? $val['amount_2013'] : 0;
$a2 = isset($val['amount_2014']) ? $val['amount_2014'] : 0;
unset($temp[$key]);
foreach($temp as $k=>$values){
if($values['brand'] == $b){
if($a1 == 0){
$a1 = isset($values['amount_2013']) ? $values['amount_2013'] : 0;
}
if($a2 == 0){
$a2 = isset($values['amount_2014']) ? $values['amount_2014'] : 0;
}
unset($temp[$k]);
}
}
if(!in_array($b, $key_array))
{
$newArr[] = array('brand' => $b, 'amount_2014' => $a2, 'amount_2013' => $a1);
}
$key_array[] = $b;
}
print_r($newArr);
This is what I used:
<?php
$arr1 = array(0=>array("brand"=>"CARTIER","amount_2014"=>136476), 1=>array("brand"=>"tiffany","amount_2014"=>22000));
$arr2 = array(0=>array("brand"=>"CARTIER","amount_2013"=>22000));
foreach ($arr2 as $key=>$value){
if( $value["brand"] == "CARTIER")
{
$arr1[0]["amount_2013"] = $value["amount_2013"];
$arr1[1]["amount_2013"] = 0;
}
else
{
$arr1[1]["amount_2013"] = $value["amount_2013"];
$arr1[0]["amount_2013"] = 0;
}
}
print_r($arr1);
?>

PHP group values from array

I have this array:
Array (
[061716v] => 1
[061610A] => 1
[062433AP] => 1
[063868M] => 2
[059173V] => 3
[061579A] => 3
[062404AP] => 3
[059179V] => 4
[061582A] => 4
[061697V] => 4
[062407AP] => 4
)
How can i get this:
Array (
[1] => 061716v,061610A,062433AP
[2] => 063868M
[3] => 059173V,061579A,062404AP
[4] => 059179V,061582A,061697V,062407AP
)
In PHP single foreach() will do the job:-
$final_array = [];
foreach($initial_array as $key=>$val){
$final_array[$val] = isset($final_array[$val]) ? $final_array[$val].','.$key : $key;
}
print_r($final_array);
Output:-https://3v4l.org/lSKE2
// You also can use implode to skip isset checks
$group = [];
foreach ($initialArray as $key => $value) {
$group[$value][] = $key;
}
$result = array_map(function($v) { return implode(",",$v); }, $group);
print_r($result);

Categories