unique array on base on value of specific key - php

I have the following array:
Array
(
[0] => Array
(
[hotelID] => 10
[hotelcategoryID] => 12
[hotelName] => Grand Forest Metsovo
[hotelShortDescription] =>
[hotelVisible] => 1
[roomID] => 2
)
[1] => Array
(
[hotelID] => 10
[hotelcategoryID] => 12
[hotelName] => Grand Forest Metsovo
[hotelShortDescription] =>
[hotelVisible] => 1
[roomID] => 3
)
[2] => Array
(
[hotelID] => 10
[hotelcategoryID] => 12
[hotelName] => Grand Forest Metsovo
[hotelShortDescription] =>
[hotelVisible] => 1
[roomID] => 4
)
[3] => Array
(
[hotelID] => 14
[hotelcategoryID] => 7
[hotelName] => Hotel Metropolis
[hotelShortDescription] =>
[hotelVisible] => 1
[roomID] => 23
)
[4] => Array
(
[hotelID] => 14
[hotelcategoryID] => 7
[hotelName] => Hotel Metropolis
[hotelShortDescription] =>
[hotelVisible] => 1
[roomID] => 24
)
)
I have two different hotelID keys. I would like to extract only one element (the first one) where the hotelID is unique in whole array. I am trying with following code:
$data['uniqueHotels'] = array_map('unserialize', array_unique(array_map('serialize', $hotels)));
but without any luck so far.
Anyone can give me a hint?

If looking for the first element:
<?php
$hotels = array(
array(
'id' => 1,
'hotelID' => 10
),
array(
'id' => 2,
'hotelID' => 10,
),
array(
'id' => 3,
'hotelID' => 20,
),
array(
'id' => 4,
'hotelID' => 20,
),
);
function getUniqueHotels($hotels) {
$uniqueHotels = array();
foreach($hotels as $hotel) {
$niddle = $hotel['hotelID'];
if(array_key_exists($niddle, $uniqueHotels)) continue;
$uniqueHotels[$niddle] = $hotel;
}
return $uniqueHotels;
}
$unique_hotels = getUniqueHotels($hotels);
print_r($unique_hotels);
results in:
Array
(
[10] => Array
(
[id] => 1
[hotelID] => 10
)
[20] => Array
(
[id] => 3
[hotelID] => 20
)
)

You could simply loop through the array and add them to a new array, indexed by hotelID. This way any duplicates will just overwrite the existing value and you end up with one entry per hotel:
$unique = array();
foreach ($hotels as $value)
{
$unique[$value['hotelID']] = $value;
}
$data['uniqueHotels'] = array_values($unique);

Here is a dynmaic solution:
function uniqueAssocArray($array, $uniqueKey){
$unique = array();
foreach ($array as $value){
$unique[$value[$uniqueKey]] = $value;
}
$data = array_values($unique);
return $data;
}
How to use:
uniqueAssocArray($yourArray, 'theKey');

along the lines of what you're trying,
array_unique(array_map(function($hotel) { return $hotel['hotelID']; }, $array))

Related

sum array indexes with same value for a specific key

I have the following array:
[0] => Array
(
[id] => 1
[uid] => 50
[sum1] => 1
[sum2] => 2
)
[1] => Array
(
[id] => 2
[uid] => 50
[sum1] => 2
[sum2] => 4
)
[2] => Array
(
[id] => 3
[uid] => 51
[sum1] => 3
[sum2] => 5
)
As you can see, on some of those indexes, [uid] is the same. The length and data of the array is dynamic.
what i need to do is merge the indexes that have the same value for[uid] and sum the values for the other keys:
[0] => Array
(
[id] => 2
[uid] => 50
[sum1] => 3
[sum2] => 6
)
[1] => Array
(
[id] => 3
[uid] => 51
[sum1] => 3
[sum2] => 5
)
But for the life of me, i can't figure out how to do that.
Any help appreciated!
You can do it like this way,
<?php
$mainArray = [
0 => Array
(
'id' => 1,
'uid' => 50,
'sum1' => 1,
'sum2' => 2
),
1 => Array
(
'id' => 2,
'uid' => 50,
'sum1' => 2,
'sum2' => 4
),
2 => Array
(
'id' => 3,
'uid' => 51,
'sum1' => 3,
'sum2' => 5
)
];
$newArray=[];
foreach ($mainArray as $value) {
if(!array_key_exists($value['uid'], $newArray)){
// Store first time
$newArray[$value['uid']] = $value;
}else{
// Already exist, then sum and replace it
$newArray[$value['uid']]['id'] = $value['id'];
$newArray[$value['uid']]['sum1'] += $value['sum1'];// Sum with previous value
$newArray[$value['uid']]['sum2'] += $value['sum2'];// Sum with previous value
}
}
$newArray = array_values($newArray);// Reset indexes, Start the array index with zero
print_r($newArray);// To see the output
Output:
Array
(
[0] => Array
(
[id] => 2
[uid] => 50
[sum1] => 3
[sum2] => 6
)
[1] => Array
(
[id] => 3
[uid] => 51
[sum1] => 3
[sum2] => 5
)
)
I think you are correct. Actually, i solved the problem using something similar:
$sumArray = Array();
foreach ($array1 as $item){
if(isset($sumArray[$item['uid']])){
$sumArray[$item['idPartener']]['sum1'] += $item['sum1'];
$sumArray[$item['idPartener']]['sum2'] += $item['sum2'];
}else{
$sumArray[$item['uid']] = Array(
'id' => $item['id'],
'sum1' => $item['sum1'],
'sum2' => $item['sum2'] ,
);
}
}
Thanks all for your help!

empty value of a key if the array has duplicates

i have this array
Array
(
[0] => Array
(
[user_id] => 78
[post_id] => 3
[post_user_added_id] => 2
)
[1] => Array
(
[user_id] => 76
[post_id] => 3
[post_user_added_id] => 16
)
[2] => Array
(
[user_id] => 78
[post_id] => 3
[post_user_added_id] => 12
)
[3] => Array
(
[user_id] => 76
[post_id] => 9
[post_user_added_id] => 15
)
[4] => Array
(
[user_id] => 77
[post_id] => 9
[post_user_added_id] => 15
)
what i want to do is if the key post_id is repeated i just want to empty it and keep one so my final array will look like this
Array
(
[0] => Array
(
[user_id] => 78
[post_id] => 3
[post_user_added_id] => 2
)
[1] => Array
(
[user_id] => 76
[post_id] =>
[post_user_added_id] => 16
)
[2] => Array
(
[user_id] => 78
[post_id] =>
[post_user_added_id] => 12
)
[3] => Array
(
[user_id] => 76
[post_id] => 9
[post_user_added_id] => 15
)
[4] => Array
(
[user_id] => 77
[post_id] =>
[post_user_added_id] => 15
)
i have tried this code but it doesn't seem to work it deletes the whole array
foreach($arry as $k => $v)
{
foreach($arry as $key => $value)
{
if($k != $key && $v['post_id'] == $value['post_id'])
{
unset($arry [$k]);
}
}
}
print_r($arry);
You can perform foreach with ternary operator
$last = null;//this will keep the previous post_id
foreach($arr as &$v){
($last && $last == $v['post_id']) ? ($v['post_id'] = '') : ($last = $v['post_id']);
}
print_r($arr);
Working example :- https://3v4l.org/RiU9J
here try this.
$tempArr = [];
$resArr = [];
foreach($orignalArr as $key=>$obj){
if(in_array($obj['post_id'], $tempArr)){
$obj['post_id'] = '';
$resArr[] = $obj;
}else{
$tempArr[] = $obj['post_id'];
$resArr[] = $obj;
}
}
print_r($resArr);
try this :
// example code
$arrayResult = array();
$arry = [
1 =>
[
'user_id' => 78,
'post_id' => 3,
'post_user_added_id' => 2
],
2=>
[
'user_id' => 76,
'post_id' => 3,
'post_user_added_id' => 16
],
3 =>
[
'user_id' => 78,
'post_id' => 3,
'post_user_added_id' => 12
],
4 =>
[
'user_id' => 76,
'post_id' => 9,
'post_user_added_id' => 15
],
5 =>
[
'user_id' => 77,
'post_id' => 9,
'post_user_added_id' => 15
]];
$final = array();
foreach($arry as $a)
{
if (in_array($a['post_id'], $arrayResult)) {
$a['post_id'] = 0;
}else{
$arrayResult[] = $a['post_id'];
}
$final[] = $a;
}
var_dump($final);
Maybe if you use a stack for comparison?
edit: rewritten the code...
$stack=[];
foreach ($array as $index => $subarray){
if(in_array($subarray['post_id'], $stack)) {
$array[$index]['post_id'] = null;
}
else $stack[]=$subarray['post_id'];
}
print_r($array);
example: https://3v4l.org/FsPUG
Hope this helps!
use of your array value in instead of $arr and try to filter array like the following code :
$arr = array(
array(
'user_id'=>15,
'post_id'=>3,
'post_user_added_id'=>2
),
array(
'user_id'=>16,
'post_id'=>3,
'post_user_added_id'=>2
),
array(
'user_id'=>18,
'post_id'=>3,
'post_user_added_id'=>2
),
array(
'user_id'=>18,
'post_id'=>3,
'post_user_added_id'=>2
),
array(
'user_id'=>16,
'post_id'=>3,
'post_user_added_id'=>2
),
);
$postids = array();
foreach($arr as $key=>$val){
if(in_array($val['post_id'], $postids)){
$arr[$key]['post_id'] = '';
}else{
$postids[] = $val['post_id'];
}
}
echo "<pre>";print_r($arr);exit;
Output :
Array
(
[0] => Array
(
[user_id] => 15
[post_id] => 3
[post_user_added_id] => 2
)
[1] => Array
(
[user_id] => 16
[post_id] =>
[post_user_added_id] => 2
)
[2] => Array
(
[user_id] => 18
[post_id] =>
[post_user_added_id] => 2
)
[3] => Array
(
[user_id] => 18
[post_id] =>
[post_user_added_id] => 2
)
[4] => Array
(
[user_id] => 16
[post_id] =>
[post_user_added_id] => 2
)
)

Create new array depending on key

My array is like that:
Array
(
[0] => Array
(
[des_id] => 1
[des_name] => bagan
[tran_id] => 1
[tran_name] => private
[tran_image] => 1251961905A1.jpg
[type] => car
[troute_id] => 10
)
[1] => Array
(
[des_id] => 1
[des_name] => bagan
[tran_id] => 2
[tran_name] => express
[tran_image] => bus3.jpg
[type] => car
[troute_id] => 13
)
[2] => Array
(
[des_id] => 1
[des_name] => bagan
[tran_id] => 3
[tran_name] => MyanmarTrain
[tran_image] => Burma-Gorteikviaduct.jpg
[type] => train
[troute_id] => 16
)
[3] => Array
(
[des_id] => 1
[des_name] => bagan
[tran_id] => 4
[tran_name] => Ayeyarwaddy Cruise
[tran_image] => boat-ChutzpahToo1.jpg
[type] => cruise
[troute_id] => 22
)
)
I want to change that array like that depending on key['type']. If array key['type'] are same, I want to change array like that:
Array
(
[car] => Array(
[0]=>Array
(
[des_id] => 1
[des_name] => bagan
[tran_id] => 1
[tran_name] => private
[tran_image] => 1251961905A1.jpg
[type] => car
[troute_id] => 10
),
[1] => Array
(
[des_id] => 1
[des_name] => bagan
[tran_id] => 2
[tran_name] => express
[tran_image] => bus3.jpg
[type] => car
[troute_id] => 13
)
),
[train]=>Array(
[0] => Array
(
[des_id] => 1
[des_name] => bagan
[tran_id] => 3
[tran_name] => MyanmarTrain
[tran_image] => Burma-Gorteikviaduct.jpg
[type] => train
[troute_id] => 16
)
[cruise]=>Array(
[0] => Array
(
[des_id] => 1
[des_name] => bagan
[tran_id] => 4
[tran_name] => Ayeyarwaddy Cruise
[tran_image] => boat-ChutzpahToo1.jpg
[type] => cruise
[troute_id] => 22
)
)
)
)
what I mean is that if key['type'] is car, I want to create car array or if the type is train I want to create train array or if the type is cruise I want to create cruise array. I don't know how to loop the array. Anyone please help me. Thanks a lot!
Here's a simple way to do it: loop over the data, and just append to the subarray matching the type value:
// starting data
$starting_array = array (
0 => array (
'des_id' => 1,
'des_name' => 'bagan',
'tran_id' => 1,
'tran_name' => 'private',
'tran_image' => '1251961905A1.jpg',
'type' => 'car',
'troute_id' => 10
),
1 => array (
'des_id' => 1,
'des_name' => 'bagan',
'tran_id' => 2,
'tran_name' => 'express',
'tran_image' => 'bus3.jpg',
'type' => 'car',
'troute_id' => 13
),
2 => array (
'des_id' => 1,
'des_name' => 'bagan',
'tran_id' => 3,
'tran_name' => 'MyanmarTrain',
'tran_image' => 'Burma-Gorteikviaduct.jpg',
'type' => 'train',
'troute_id' => 16
),
3 => array (
'des_id' => 1,
'des_name' => 'bagan',
'tran_id' => 4,
'tran_name' => 'Ayeyarwaddy Cruise',
'tran_image' => 'boat-ChutzpahToo1.jpg',
'type' => 'cruise',
'troute_id' => 22
)
);
// initialize the result array
$result = array();
// loop over the starting array
foreach($starting_array as $entry) {
// make sure the result array has a key matching this item's type
if(!array_key_exists($entry['type'], $result)) {
$result[ $entry['type'] ] = array();
}
// add this item to the result array
$result[ $entry['type'] ][] = $entry;
}
// this is just for testing, so you can verify the output matches your desired result
echo "<pre>";
var_dump($result);
echo "</pre>";
Try this:
<?php
$tempArr = Array
(
Array(
"des_id" => 1,
"des_name" => "bagan",
"tran_id" => 1,
"tran_name" => "private",
"tran_image" => "1251961905A1.jpg",
"type" => "car",
"troute_id" => 10
),
Array
(
"des_id" => 1,
"des_name" => "bagan",
"tran_id" => 2,
"tran_name" => "express",
"tran_image" => "bus3.jpg",
"type" => "car",
"troute_id" => 13
),
Array
(
"des_id" => 1,
"des_name" => "bagan",
"tran_id" => 3,
"tran_name" => "MyanmarTrain",
"tran_image" => "Burma-Gorteikviaduct.jpg",
"type" => "train",
"troute_id" => 16
),
Array
(
"des_id" => 1,
"des_name" => "bagan",
"tran_id" => 4,
"tran_name" => "Ayeyarwaddy Cruise",
"tran_image" => "boat-ChutzpahToo1.jpg",
"type" => "cruise",
"troute_id" => 22
)
);
$resultArr = array();
foreach($tempArr as $tempKey=>$temp)
{
if(!array_key_exists($temp['type'], $resultArr))
{
$resultArr[$temp['type']] = array();
}
$resultArr[$temp['type']][] = $temp;
}
echo '<pre>';
print_r($resultArr);
?>
This is working fine .....

Convert PHP "grouped" array to "segmented" array

Trying to convert a "grouped" multidimensional array to a "segmented" multidimensional array. Not sure how to explain it exactly so hopefully these print_r results explain it better.
Current Array
Array
(
[qty] => Array
(
[0] => 1
[1] => 1
[2] => 1
)
[item_id] => Array
(
[0] => RR332
[1] => FF586
[2] => QW865
)
[item_name] => Array
(
[0] => Widget 1
[1] => Widget 2
[2] => Widget 3
)
[price] => Array
(
[0] => 1.00
[1] => 1.50
[2] => 1.50
)
)
Wanted Array
Array
(
[0] => Array
(
[qty] => 1
[item_id] => RR332
[item_name] => Widget 1
[price] => 1.00
)
[1] => Array
(
[qty] => 1
[item_id] => FF586
[item_name] => Widget 2
[price] => 1.50
)
[2] => Array
(
[qty] => 1
[item_id] => QW865
[item_name] => Widget 3
[price] => 1.50
)
)
This seems like it should be a simple task but I haven't been able to crack it yet.
I would preferably like to loop through the Current Array to create the Wanted Array if possible.
Any help is greatly appreciated!
Thanks.
You mean this?:
$data = array(
'qty' => array(
0 => 1,
1 => 1,
2 => 1,
),
'item_id' => array(
0 => 'RR332',
1 => 'FF586',
2 => 'QW865',
),
'item_name' => array(
0 => 'Widget 1',
1 => 'Widget 2',
2 => 'Widget 3',
),
'price' => array(
0 => '1.00',
1 => '1.50',
2 => '1.50',
),
);
$result = array();
foreach($data as $key => $values)
{
foreach($values as $number => $value)
$result[$number][$key] = $value;
}
print_r($result);
Output:
Array
(
[0] => Array
(
[qty] => 1
[item_id] => RR332
[item_name] => Widget 1
[price] => 1.00
)
[1] => Array
(
[qty] => 1
[item_id] => FF586
[item_name] => Widget 2
[price] => 1.50
)
[2] => Array
(
[qty] => 1
[item_id] => QW865
[item_name] => Widget 3
[price] => 1.50
)
)
I think this will do the job for you, though I don't have a good data set to test against.
$wanted_array = array();
// Iterate over the outer array to get the text keys & inner arrays
foreach ($current_array as $txtkey=>$arr) {
// Iterate over each inner array to get the numeric key
foreach ($arr as $numkey=>$val) {
// Set a numeric key pointing to a new array
// onto the new outer array if it isn't already there
if (!isset($wanted_array[$numkey])) $wanted_array[$numkey] = array();
// Swap the keys of the outer and inner arrays.
$wanted_array[$numkey][$txtkey] = $val;
}
}
Update: Using test array from #hakre's answer, here it is in practice:
$current_array = array(
'qty' => array(
0 => 1,
1 => 1,
2 => 1
),
'item_id' => array(
0 => 'RR332',
1 => 'FF586',
2 => 'QW865'
),
'item_name' => array(
0 => 'Widget 1',
1 => 'Widget 2',
2 => 'Widget 3'
),
'price' => array(
0 => '1.00',
1 => '1.50',
2 => '1.50'
)
);
// Output:
Array
(
[0] => Array
(
[qty] => 1
[item_id] => RR332
[item_name] => Widget 1
[price] => 1.00
)
[1] => Array
(
[qty] => 1
[item_id] => FF586
[item_name] => Widget 2
[price] => 1.50
)
[2] => Array
(
[qty] => 1
[item_id] => QW865
[item_name] => Widget 3
[price] => 1.50
)
)
Like you said, just loop through it to build it.
$wanted = array();
foreach($current['item_id'] as $key => $value) {
$wanted[$key] = array(
'qty' = $current['qty'][$key],
'item_id' = $current['item_id'][$key],
'item_name' = $current['item_name'][$key],
'price' = $current['price'][$key]
);
}
print_r($wanted);
You can loop over your original array using the foreach loop, which gives you the $key, and $value for each item in your array. From there, construct your new array as you like.
$array2 = array();
foreach ($array1 as $key => $value)
{
$array2[] = array('key' => 'value');
}

Merge arrays (PHP)

How combine arrays in this way?
source:
Array
(
[0] => Array
(
[id] => 3
[title] => book
[tval] => 10000
)
[1] => Array
(
[id] => 3
[title] => book
[tval] => 1700
)
[3] => Array
(
[id] => 27
[title] => fruit
[tval] => 3000
)
.......
)
result:
Array
(
[0] => Array
(
[id] => 3
[title] => book
[tval] => 10000,1700
)
[1] => Array
(
[id] => 27
[title] => fruit
[tval] => 3000
)
.......
)
please help to solve this problem,
thanks!!!
sorry for bad english(
This should work:
$result = array();
foreach($array as $elem) {
$key = $elem['id'];
if (isset($result[$key])) {
$result[$key]['tval'] .= ',' . $elem['tval'];
} else {
$result[$key] = $elem;
}
}
This basically groups elements by id, concatenating tvals (separated by ,).
Simply building slightly on user576875's method:
$a = array ( 0 => array ( 'id' => 3,
'title' => 'book',
'tval' => 10000
),
1 => array ( 'id' => 3,
'title' => 'book',
'tval' => 1700
),
3 => array ( 'id' => 27,
'bcalias' => 'fruit',
'tval' => 3000
)
);
$result = array();
foreach ($a as $elem) {
$key = $elem['id'];
if (isset($result[$key])) {
$result[$key]['tval'] .= ',' . $elem['tval'];
} else {
$result[$key] = $elem;
}
}
$result = array_merge($result);
var_dump($result);
gives a result of:
array
0 =>
array
'id' => int 3
'title' => string 'book' (length=4)
'tval' => string '10000,1700' (length=10)
1 =>
array
'id' => int 27
'bcalias' => string 'fruit' (length=5)
'tval' => int 3000
The only real difference is the array_merge() to reset the keys

Categories