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);
}
Related
This question already has answers here:
Filter/Remove rows where column value is found more than once in a multidimensional array
(4 answers)
Closed 9 months ago.
Need help for the code.
Here is my list of array which i want to remove the two (2) Wi-fi.
Array
(
[20-10] => Array
(
[facilityCode] => 20
[facilityGroupCode] => 10
[order] => 1
[number] => 1968
[voucher] =>
[description] => Year of construction
)
[550-70] => Array
(
[facilityCode] => 550
[facilityGroupCode] => 70
[order] => 1
[indFee] =>
[indYesOrNo] => 1
[voucher] =>
[description] => Wi-fi
)
[20-60] => Array
(
[facilityCode] => 20
[facilityGroupCode] => 60
[order] => 1
[indLogic] => 1
[voucher] =>
[description] => Shower
)
[261-60] => Array
(
[facilityCode] => 261
[facilityGroupCode] => 60
[order] => 1
[indFee] =>
[indYesOrNo] => 1
[voucher] =>
[description] => Wi-fi
)
)
I do also tried the array_unique();
here is the result:
Array
(
[0] => Year of construction
[1] => Shower
[2] => Wi-fi
)
But i want to keep the facilityCode,facilityGroupCode,order,number etc.
Thanks for any help.
One liner is all can do your requirement,
$result = array_reverse(array_values(array_column(array_reverse($arr), null, 'description')));
Source link for your requirement.
//populate data
$mainArr = array();
$first = array(
"facilityCode" => 20,
"facilityGroupCode" => 10,
"order" => 1,
"number" => 1968,
"voucher" => "",
"description" => "Year of construction",
);
$second = array(
"facilityCode" => 550,
"facilityGroupCode" => 70,
"order" => 1,
"indFee" => "",
"indYesOrNo" => 1,
"voucher" => "",
"description" => "Wi-fi"
);
$mainArr["20-10"] = $first;
$mainArr["550-70"] = $second;
$mainArr["261-60"] = $second;
//get duplicates
$counter = 0;
$duplicates = array();
foreach ($mainArr as $key=>$val) {
$counter++;
if (in_array($key, $duplicates)) continue;
$i = 0;
foreach ($mainArr as $key1=>$val1) {
if ($i < $counter) {
$i++;
continue;
}
if ($val["description"] == $val1["description"]) {
array_push($duplicates, $key1);
}
}
}
//remove duplicates
foreach($duplicates as $key) {
unset($mainArr[$key]);
}
$itemRows = array(); // Your main array
$descriptionValues = array();
foreach ($itemRows as $itemKey => $itemRow) {
foreach ($itemRow as $key => $value) {
if ($key == 'description') {
if (in_array($value, $descriptionValues)) {
unset($itemRows[$itemKey]);
continue 2;
}
$descriptionValues[] = $value;
}
}
}
In my input array, I have multiple rows with a userTag of All, but I only want a maximum of one. Other rows my have duplicated userTag values (such as Seeker), but extra All rows must be removed.
$input = [
0 => ['userTag' => 'All', 'fbId' => 10210118553469338, 'price' => 70],
1 => ['userTag' => 'All', 'fbId' => 10210118553469338, 'price' => 14],
2 => ['userTag' => 'All', 'fbId' => 10210118553469338, 'price' => null],
3 => ['userTag' => 'Seeker', 'fbId' => 10207897577195936, 'price' => 65],
6 => ['userTag' => 'Seeker', 'fbId' => 709288842611719, 'price' => 75],
17 => ['userTag' => 'Trader', 'fbId' => 2145752308783752, 'price' => null]
];
My current code:
$dat = array();
$dat2 = array();
foreach ($input as $key => $value)
{
$i = 0;
$j = 0;
if (count($dat) == 0) {
$dat = $input[$key];
$i++;
} else {
if ($input[$key]['userTag'] == "All") {
if ($this->check($input[$key]['fbId'], $dat) == false) {
$dat[$i] = $input[$key];
$i++;
}
} else {
$dat2[$j] = $input[$key];
$j++;
}
}
}
$data = array_merge($dat, $dat2);
return $data;
The check() function:
public function check($val, $array) {
foreach ($array as $vl) {
if ($val == $array[$vl]['fbId']) {
return true;
break;
}
}
return false;
}
You can try something simple like this:
$data = [];
foreach($input as $key => $value)
{
$counter = 0;
if($value['userTag'] =="All"){
if($counter == 0 ) {//test if is the first userTag == All
$counter = 1;//increment the counter so the if doesn't trigger and the value isn't appended
$data[] = $value;//add it to the array
}
} else {
$data[] = $value;//keep the rest of the values
}
}
return $data;
You can use the below code, This will remove all duplicate values from your array.
$arr = array_map("unserialize", array_unique(array_map("serialize", $arr)));
UPDATED ANSWER
The updated answer below is the accurate solution asked in the question which helps with All rows data too.
$temp = array();
foreach($arr as $key => $val) {
if ($val['userTag'] == "All" && empty($temp)) {
$temp[$key] = $arr[$key];
unset($arr[$key]);
}
else if ($val['userTag'] == "All") {
unset($arr[$key]);
}
}
$arr = array_merge($arr, $temp);
Check this code. Perfectly working.
$n_array = array();$i=0;
foreach($array as $row){
if($row['userTag']=="All"){
if($i==0){
$n_array[]=$row;
$i=1;
}
}
else $n_array[]=$row;
}
echo "<pre>";print_r($n_array);
Result
Array
(
[0] => Array
(
[userTag] => All
[fbId] => 10210118553469338
[fName] => Danish
[lName] => Aftab
[imageUrl] => https://scontent.xx.fbcdn.net/v/t1.0-1/p50x50/22491765_10210410024475931_8589925114603818114_n.jpg?oh=7fa6266e7948ef2d218076857972f7e0
[subsType] => gold
[user_visible] => 0
[distance] => 0.01
[advising] => 0
[avgRate] => 4
[totalReview] => 2
[us_seeker_type] => new
[price] => 70
)
[1] => Array
(
[userTag] => Seeker
[fbId] => 10207897577195936
[fName] => Saq
[lName] => Khan
[imageUrl] => https://scontent.xx.fbcdn.net/v/t1.0-1/p50x50/21151741_10207631130774942_8962953748374982841_n.jpg?oh=f5e5b9dff52b1ba90ca47ade3d703b01
[subsType] => gold
[user_visible] => 0
[background] =>
[topic] =>
[distance] => 0.01
[advising] => 0
[avgRate] => 0
[totalReview] => 0
[us_seeker_type] => new
[price] => 65
)
[2] => Array
(
[userTag] => Seeker
[fbId] => 709288842611719
[fName] => Muhammad
[lName] => Hasan
[imageUrl] => https://scontent.xx.fbcdn.net/v/t1.0-1/p50x50/20264704_681395725401031_2098768310549259034_n.jpg?oh=36db5b6ed60214088750794d4e3aa3e6
[subsType] => gold
[user_visible] => 0
[distance] => 0.02
[advising] => 0
[avgRate] => 0
[totalReview] => 0
[us_seeker_type] => new
[price] => 75
)
[3] => Array
(
[userTag] => Trader
[fbId] => 2145752308783752
[fName] => Jawaid
[lName] => Ahmed
[imageUrl] => https://scontent.xx.fbcdn.net/v/t1.0-1/p50x50/20992899_2068273703198280_4249128502952085310_n.jpg?oh=6df0be6ced405dd66ee50de238156183
[subsType] => basic
[user_visible] => 0
[advising] => 0
[distance] => 0
[avgRate] => 0
[totalReview] => 0
[utr_trader_type] => new
[price] =>
)
)
To keep only the first occurrence of the All row, build an array where All is used as a first level key in the result array. If the row isn't an All row, just keep using its original numeric key. Using the ??= "null coalescing assignment operator", you ensure that only the first All value is stored and all subsequently encountered All rows are ignored.
Code: (Demo)
$result = [];
foreach ($array as $key => $row) {
$result[$row['userTag'] === 'All' ? 'All' : $key] ??= $row;
}
var_export($result);
If you don't want to have the All key for later processing reasons, you can replace it by un-setting then re-pushing it into the array (after finishing the loop).
$result[] = $result['All']; // or unshift($result, $result['All']) to the start of the array
unset($result['All']);
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
)
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);
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);