PHP group values from array - php

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

Related

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.

Merge 2 element of same array into one in php

I have an array
Array
(
[0] => Array
(
[hrg_lid] => 214291464161204318
[pecon] => 0
[col2pe] => Karam
[col4pe] => 1
[col6pe] => 2
[col8pe] => 264
[col9pe] => 42
[col10pe] => 85
[col11pe] => 2
)
[1] => Array
(
[hrg_lid] => 707581464079555092
[pecon] => 1
[col2pe] => Dummy
[col4pe] =>
[col6pe] =>
[col8pe] => 12
[col9pe] => 0
[col10pe] => 0
[col11pe] => 2
[col12pe] => 1
[col13pe] => 1
)
[2] => Array
(
[hrg_lid] => 707581464079555092
[col5risk] => 2
[col6risk] => 2
[col7risk] => 1
[col8risk] => 2
[col9risk] => 1
[col10risk] => 1
[col11risk] => 2
)
I want to merge those elements which has same hrg_lid.
Expected Output
Array
(
[0] => Array
(
[hrg_lid] => 214291464161204318
[pecon] => 0
[col2pe] => Karam
[col4pe] => 1
[col6pe] => 2
[col8pe] => 264
[col9pe] => 42
[col10pe] => 85
[col11pe] => 2
)
[1] => Array
(
[hrg_lid] => 707581464079555092
[pecon] => 1
[col2pe] => Dummy
[col4pe] =>
[col6pe] =>
[col8pe] => 12
[col9pe] => 0
[col10pe] => 0
[col11pe] => 2
[col12pe] => 1
[col13pe] => 1
[col5risk] => 2
[col6risk] => 2
[col7risk] => 1
[col8risk] => 2
[col9risk] => 1
[col10risk] => 1
[col11risk] => 2
)
I tried following code
foreach($arr as $key => $value) {
$finalArray[$value['hrg_lid']] = $value;
}
but fails
I would use hrg_lid as array key - otherwise you have to check every element already in the output array for matches every time you add a new element:
$finalArray = array();
foreach($arr as $value) {
$hrg_lid = $value['hrg_lid'];
if (isset($finalArray[$hrg_lid])) {
// merge if element with this $hrg_lid is already present
$finalArray[$hrg_lid] = array_merge($finalArray[$hrg_lid], $value);
} else {
// save as new
$finalArray[$hrg_lid] = $value;
}
}
If you want to get normalized array keys, you can reset them afterwards:
$finalArray = array_values($finalArray);
The hrg_lid value must be the key of the array, if you won't change the keys, Try this :
for($i=0; $i < count($arr);$i++)
{
for($j=0; $j < count($finalArray);$j++)
{
if($arr[$i]['hrg_lid'] == $finalArray[$j]['hrg_lid'])
{
$finalArray[$j] = array_merge($finalArray[$j],$arr[$i]);
break;
}
}
}
Try soomething like :
$finalArray = [];
foreach($arr as $singleArray) {
$id = $singleArray['hrg_lid'];
if (isset($finalArray[$id])) {
$finalArray = array_merge($finalArray[$id], $singleArray);
} else {
$finalArray[] = $singleArray;
}
}
You could try something like that :
$tmpArray = array();
$finalArray = array();
// We merge the arrays which have the same value in 'hrg_lid' col
foreach($source as $array){
$key = $array['hrg_lid'];
array_shift($array);
if(array_key_exists($key, $tmpArray)){
$tmpArray[$key] = array_merge($tmpArray[$key], $array);
}else{
$tmpArray[$key] = $array;
}
}
// We build the final array
foreach($tmpArray as $key => $value){
$finalArray[] = array_merge(array('hrg_lid' => $key), $value);
}

How to merge values in foreach loop php

I am working in multidimensional array, i have an array like this and i want to merge array
[0] => Array
(
[QuizId] => 173
[QuizName] => Reprocessing Surgical Drapes and Gowns
[totalexams] => 1
[UserScore] => 8
[MaxScore] => 20
[passed] => 1
[CategoryId] => 1
[CategoryName] => CRCST
[totalTimes] => 1
[orderId] => 19
[productId] => 50
)
[1] => Array
(
[QuizId] => 173
[QuizName] => Reprocessing Surgical Drapes and Gowns
[totalexams] => 1
[UserScore] => 8
[MaxScore] => 20
[passed] => 1
[CategoryId] => 1
[CategoryName] => CRCST
[totalTimes] => 1
[orderId] => 20
[productId] => 50
)
All i need is to make array by join orderId 19,20
ie,
[0] => Array
(
[QuizId] => 173
[QuizName] => Reprocessing Surgical Drapes and Gowns
[totalexams] => 1
[UserScore] => 8
[MaxScore] => 20
[passed] => 1
[CategoryId] => 1
[CategoryName] => CRCST
[totalTimes] => 1
[orderId] => 19,20
[productId] => 50
)
I want to arrange like this.please help me to achieve this
You can try something like this
//This is your old array that you describe in your first code sample
$old_array = array();
// This will be the new joined array
$new = array();
// This will hold the key-pairs for each array within your initial array
$temp = array();
// This will hold all the values of orderId
$orderId = array();
// Loop through each first-level array with the original array
foreach($old_array as $val) {
//Loop through each second-level array
foreach($val as $key => $value) {
// Set the key-pair values in the $temp array
$temp[$key] = $temp[$value];
if($key == "orderId") {
// Add the current orderId value to the orderId array
array_push($orderId,$value);
// Join all the orderId values into the $temp array
$temp[$key] = join(",", $orderId);
}
}
}
//Push the final values to the new array to get a 2 dimensional array
array_push($new, $temp);
Note: I did not test any of the following code so it is very likely to not work at first.
This is also VERY bad array design and there are more likely easier and more practical solutions to this problem, but you will need to give more details on what you want to achieve
$original_array = array(); //this is the array you presented
$new_array = array(); //this is the output array
foreach($original_array as $arr) {
foreach($arr as $key => $value) {
if(array_key_exists($key, $new_array)) { //if you already assigned this key, just concat
$new_array[0][$key] .= "," . $value;
} else { //otherwise assign it to the new array
$new_array[0][$key] = $value;
}
}
}
It will give you the desired result
$arrNew = array();
$i = 0;
foreach($multiDArray as $array)
{
foreach($array as $key=>$value)
{
if($i > 0)
{
if($arrNew[$key] != $value)
{
$str = $arrNew[$key].','.$value;
$arrNew[$key] = $str;
}
}
else
{
$arrNew[$key] = $value;
}
}
$i++;
}
print_r($arrNew);
Result:
Array
(
[QuizId] => 173
[QuizName] => Reprocessing Surgical Drapes and Gowns
[totalexams] => 1
[UserScore] => 8
[MaxScore] => 20
[passed] => 1
[CategoryId] => 1
[CategoryName] => CRCST
[totalTimes] => 1
[orderId] => 19,20
[productId] => 1
)

Splitting Array

I have an array of objects.
What I need is to take each [name] of each object in put into another array, but I don't want duplicates.
How can I do it?
Array (
[0] => ADOFetchObj Object
(
[name] => Team 1
[att] => None
[idGrupo] => 1
[idModulo] => 4
[ler] => 1
[escrever] => 1
[excluir] => 1
)
[1] => ADOFetchObj Object
(
[name] => Team 1
[nomeModulo] => Aplicar Juros
[idGrupo] => 1
[idModulo] => 1006
[ler] => 1
[escrever] => 1
[excluir] => 1
)
[2] => ADOFetchObj Object
(
[name] => Team 2
[att] => None
[idGrupo] => 1
[idModulo] => 10
[ler] => 1
[escrever] => 1
[excluir] => 1
)
[3] => ADOFetchObj Object
(
[name] => Team 2
[att] => None
[idGrupo] => 1
[idModulo] => 1012
[ler] => 1
[escrever] => 1
[excluir] => 1
)
)
Thanks!
You can do this:
$names = array();
foreach($arr as $list) {
$names[$list->name] = true; // can be *any* arbitrary value
}
$names = array_keys($names);
This will work because by definition array keys have to be unique.
array_unique(array_map(function($element) {
return $element->name;
}, $my_array));
There you go
$res = array();
foreach($arr as $var)
{
if(!in_array($var->name, $res))
{
$res[] = $var->name;
}
}
First, copy the names to a new array:
$arrNames = array();
foreach($arrOriginal as $objObject) {
array_push(
$arrNames,
$objObject->name
);
}
Then remove the duplicate names:
$arrNames = array_unique($arrNames);
$n = array();
foreach($array as $d) $n[] = $d->name;
$n = array_unique($n);

Select arrays with multiple occurence from a array of arrys - 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);

Categories