Remove duplicate combination of elements from multidimensional array - php

I have an array with fields:
$products = array(
[0] => array('name' => 'product_one', 'category' => 'category_one', employee => '3234'),
[1] => array('name' => 'product_two', 'category' => 'category_two', employee => '5421'),
[2] => array('name' => 'product_three', 'category' => 'category_one', employee => '3234'),
[3] => array('name' => 'product_one', 'category' => 'category_one', employee => '2153'),
[4] => array('name' => 'product_one', 'category' => 'category_two', employee => '6312')
)
Now, in this case, employee field is not important, but the combination of product/category is unique.
Wanted result:
$products = array(
[0] => array('name' => 'product_one', 'category' => 'category_one', employee => '3234'),
[1] => array('name' => 'product_two', 'category' => 'category_two', employee => '5421'),
[2] => array('name' => 'product_three', 'category' => 'category_one', employee => '3234'),
[4] => array('name' => 'product_one', 'category' => 'category_two', employee => '6312')
)
Any idea what is the best way to do this? On production, I have more than 30.000 elements and usually around 10 duplicates. Also in real database, I have 12 fields and a combination of 4 of them needs to be unique).

If you don't mind which of the duplicates you keep, it's probably simplest to iterate over the loop, making a new array with keys which are a combination of the required unique values (I've used a separator of ## in this code, you can use anything that cannot occur in the values). This way duplicates will be automatically removed as an array cannot have identical keys. Once the loop is done the output array can be re-indexed numerically using array_values:
$output = array();
foreach ($products as $p) {
$output["{$p['name']}##{$p['category']}"] = $p;
}
$output = array_values($output);
print_r($output);
Output (for your sample data):
Array
(
[0] => Array
(
[name] => product_one
[category] => category_one
[employee] => 2153
)
[1] => Array
(
[name] => product_two
[category] => category_two
[employee] => 5421
)
[2] => Array
(
[name] => product_three
[category] => category_one
[employee] => 3234
)
[3] => Array
(
[name] => product_one
[category] => category_two
[employee] => 6312
)
)
Demo on 3v4l.org

Related

Php check and replace if value exist in multi array?

Problem:
I dont know/understand how to check if date and place exists on the same "row" and they exists more then once.
Second, how do i then merge an array
my case MergeArray with ArraySchedule
Code:
$ArraySchedule = array();
while ($data = $stmt -> fetch(PDO::FETCH_ASSOC)) {
$schedules = array(
"id" => $data['id'],
"name" => $data['name'],
"date" => $data['date'],
"time" => $data['time'],
"place_id" => $data['place_id'],
"place" => $data['place'],
);
array_push($ArraySchedule, $schedules);
}
$dupe_array = array();
foreach ($ArraySchedule as $key => $value) {
if(++$dupe_array[$value["date"]] > 1 && ++$dupe_array[$value["place_id"]] > 1 ){
// this statement is wrong, i want something like:
// if date and place_id exists on the same "row" and they exists more then once
}
}
What i want to do:
Check if ArraySchedule contains schedules that have the same date and place,
if there is more than one schedule that has the same date and place_id.
then I want to update ArraySchedule with this structure
$MergeArray = array(
"id" => ArraySchedule['id'],
"name" => array(
"name" => scheduleSameDateAndPlace['name'],
"name" => scheduleSameDateAndPlace['name'],
"name" => scheduleSameDateAndPlace['name'],
),
"date" => $ArraySchedule['date'],
"time" => $ArraySchedule['time'],
"place_id" => $ArraySchedule['place_id'],
"place_name" => $ArraySchedule['place_name'],
),
MergeArray with ArraySchedule?
anyway...
Output I think I want?
Print_r($ArraySchedule)
array(
[0] =>
array(
[id] => 1
[names] => Simon
[date] => 2019-01-02
[time] 18.00
[place_id] => Tystberga Park
[place] => Tystberga
)
[1] =>
array(
[id] => 2
//[names] insted of [name]?
[names] =>
array(
[name] => Vincent
[name] => Angel
[name] => Kim
)
[date] => 2019-02-17
[time] => 13.00
[place_id] => Borås Park
[place] => Borås
)
[2] =>
array(
[id] => 3
// [names] is always an array?
[names] => Caitlyn
[date] => 2019-03-15
[time] 13.00
[place_id] => Plaza Park
[place] => EvPark
)
)
You can use array-reduce. Consider the following:
function mergeByDateAndPlace($carry, $item) {
$key = $item["place_id"] . $item["date"]; // creating key matching exact place and date
if (!isset($carry[$key])) {
$carry[$key]["name"] = $item["name"];
} else {
$carry[$key] = $item;
$item["name"] = [$item["name"]]; // make default array with 1 element so later can be append other names
}
return $carry;
}
Now use it with:
$MergeArray = array_reduce($ArraySchedule, "mergeByDateAndPlace", []);
If you later want to know if there were any duplicate you can just loop on $MergeArray. You can also use array_values if you want to discard the concat keys.
Notice #Nick 2 important comment about saving the first loop and the "time" value that need to be decided. Also notice your desire output contain multi element with the same key ("name") - you need to append them with int key - Array can not have duplicate keys.
Hope that helps!
Here is my data from my database:
var_export($ArraySchedule)
array (
0 => array ( 'id' => '225', 'place_id' => 'Alviks Kulturhus', 'name' => 'BarraBazz', 'date' => '2019-03-19', 'placeadress' => 'Gustavslundsvägen 1', ),
1 => array ( 'id' => '229', 'place_id' => 'Axelhuset Göteborg', 'name' => 'Anders Björk', 'date' => '2019-04-08', 'placeadress' => 'Axel Dahlströms torg 3', ),
2 => array ( 'id' => '230', 'place_id' => 'Axelhuset Göteborg', 'name' => 'Black Jack', 'date' => '2019-04-08', 'placeadress' => 'Axel Dahlströms torg 3', ),
3 => array ( 'id' => '227', 'place_id' => 'Arosdansen Syrianska Kulturcentret', 'name' => 'BarraBazz', 'date' => '2019-05-08', 'placeadress' => 'Narvavägen 90', ),
4 => array ( 'id' => '228', 'place_id' => 'Aspåsnäset', 'name' => 'Blender', 'date' => '2019-05-25', 'placeadress' => 'Aspåsnäset 167', ),
5 => array ( 'id' => '226', 'place_id' => 'Arenan Västervik Resort', 'name' => 'Blender', 'date' => '2019-06-29', 'placeadress' => 'Lysingsvägen', ),
6 => array ( 'id' => '222', 'place_id' => 'Alingsåsparken', 'name' => 'Bendéns', 'date' => '2019-07-16', 'placeadress' => 'Folkparksgatan 3A', ),
7 => array ( 'id' => '223', 'place_id' => 'Alingsåsparken', 'name' => 'Charlies', 'date' => '2019-07-16', 'placeadress' => 'Folkparksgatan 3A', ),
8 => array ( 'id' => '224', 'place_id' => 'Allhuset Södertälje', 'name' => 'Cedrix', 'date' => '2019-07-16', 'placeadress' => 'Barrtorpsvägen 1A', ), )
I want to update the "name" with an array of names everytime that place_id and date are the same.
This is the output I want:
Array (
[0] =>
Array ( [id] => 225 [place_id] => Alviks Kulturhus [name] => BarraBazz [date] => 2019-03-19 [placeadress] => Gustavslundsvägen 1 )
[1] =>
Array ( [id] => 229 [place_id] => Axelhuset Göteborg [name] => Array([0] => Anders Björk [1] => Black Jack ) [date] => 2019-04-08 [placeadress] => Axel Dahlströms torg 3 )
[3] =>
Array ( [id] => 227 [place_id] => Arosdansen Syrianska Kulturcentret [name] => BarraBazz [date] => 2019-05-08 [placeadress] => Narvavägen 90 )
[4] =>
Array ( [id] => 228 [place_id] => Aspåsnäset [name] => Blender [date] => 2019-05-25 [placeadress] => Aspåsnäset 167 )
[5] =>
Array ( [id] => 226 [place_id] => Arenan Västervik Resort [name] => Blender [date] => 2019-06-29 [placeadress] => Lysingsvägen )
[6] =>
Array ( [id] => 222 [place_id] => [Alingsåsparken] [name] => Array([0] => Bendéns [1] => Charlies) [date] => 2019-07-16 [placeadress] => Folkparksgatan 3A )
[8] =>
Array ( [id] => 224 [place_id] => Allhuset Södertälje [name] => Cedrix [date] => 2019-07-16 [placeadress] => Barrtorpsvägen 1A ) )
Here is my updated code
$sql = "SELECT `schedule`.`id`,`schedule`.`place_id`,`schedule`.`name`,`schedule`.`date`,`places`.`placeadress` FROM `schedule` INNER JOIN `places` ON `schedule`.`place_id`=`places`.`place_id` ORDER BY `date`";
$stmt = $db -> prepare($sql);
$stmt -> execute();
$ArraySchedule = $stmt->fetchAll(PDO::FETCH_ASSOC);
var_export($ArraySchedule);
$DatePlace = array();
foreach ($ArraySchedule as $key => $Schedule){
$Arrayquery = "SELECT `schedule`.`id`,`schedule`.`place_id`,`schedule`.`name`,`schedule`.`date`,`places`.`placeadress` FROM `schedule` INNER JOIN `places` ON `schedule`.`place_id`=`places`.`place_id` WHERE `schedule`.`date`= :date_ AND `schedule`.`place_id` = :place_id ORDER BY `date`";
$ArrayStmt = $db->prepare($Arrayquery);
$ArrayStmt -> execute(array(":date_" => $Schedule['date'],":place_id" => $Schedule['place_id']));
//Getting every $Schedule that has the same date and place_id
if($ArrayStmt->rowCount() > 1){
//Here i want two update the name inside
//$ArrayArraySchedule with an array of names
//that has the same place and date?
}
}
print_r($ArraySchedule);

codeigniter insert multi-dimensional array to the database

Hello I have this multi dimensional array which needs to be inserted to the database table.
so far I have come up with this solution which don't work fully. I have a form that support dynamic fields many dynamic fields. I want to save those dynamically created fields using this function. First I had been able to create a loop to format the data.
I used this loop to format the data
$url = str_replace(' ','-',strtolower($this->input->post('title')));
$data = ['business' => [
'title' => $this->input->post('title'),
'URL' => $url,
'category' => $this->input->post('category'),
'region' => $this->input->post('region')
],
'description_' => [
'text' => $this->input->post('description'),
],
'logo_' => [
'blob' => $this->input->post('logo'),
]];
$nyingi = [ 'location_' => ['text' => 'loc_txt','priority' => 'loc_order'],
'photo_' => ['path' => 'p_txt'],
'video_' => ['path' => 'v_txt'],
'product_' => ['p_id' => 'pt_q', 'text' => 'pt_txt', 'expire' => 'pt_xpr', 'title' => 'pt_tt'],
'service_' => ['p_id' => 'st_q', 'text' => 'st_txt', 'expire' => 'st_xpr', 'title' => 'st_tt'],
'hours_' => ['time1' => 't1', 'time2' => 't2', 'type' => 'tt'],
'map_' => ['text' => 'm_txt']
];
foreach($nyingi as $ins => $vl){
foreach($vl as $fld => $box){
$uwazi = $this->input->post($box);
if(is_array($uwazi) && 1<count($uwazi)){
foreach($uwazi as $bb){
$one[$ins][$fld][] = $bb;
}
} elseif(is_array($uwazi) && 1==count($uwazi)) {
print_r($uwazi);
}
}
}
for($g=0;$g<count($one);$g++){
for($h=0;$h<count($one[$g]);$h++){
for($z=0;$z<count($one[$g][$h]);$z++){
//if(array_key_exists($one[$g][$h+1], $one)){
print $one[$g][$h][$z+1];
//}
}
}
}
$data = array_merge($data, $one);
The output of the above code
[location_] => Array
(
[text] => Array
(
[0] => Lemara Main Office
[1] => Themi branch
[2] => Sinoni branch
)
[priority] => Array
(
[0] => 1
[1] => 2
[2] => 3
)
)
[photo_] => Array
(
[path] => Array
(
[0] => lemaraphoto.png
[1] => themiphoto.png
[2] => sinoniphoto.png
)
)
[video_] => Array
(
[path] => Array
(
[0] => lemaravideo.mp4
[1] => themivideo.mp4
[2] => sinonivideo.mp4
)
)
[product_] => Array
(
[p_id] => Array
(
[0] => product photo
[1] => product 3 photo
[2] => Product 2 photo
)
[text] => Array
(
[0] => product desc
[1] => product 3 desc
[2] => product 2 desc
)
[expire] => Array
(
[0] => product expire
[1] => product 3 expire
[2] => Product 2 expire
)
[title] => Array
(
[0] => product
[1] => Product 3
[2] => Product 2
)
)
[service_] => Array
(
[p_id] => Array
(
[0] => Service 2 photo
[1] => service 3 photo
[2] => service photo
)
[text] => Array
(
[0] => service 2 desc
[1] => service 3 desc
[2] => service desc
)
[expire] => Array
(
[0] => Service 2 expire
[1] => service 3 expire
[2] => service expire
)
[title] => Array
(
[0] => Service 2
[1] => service 3
[2] => service
)
)
)
I have this add_bz function
function add_bz($data){
$this->db->trans_start(); $er=0;
foreach($data as $table => $sql){
if($table==="business"){
$this->db->insert($table, $sql);
$id = $this->db->insert_id();
} else {
array_merge($sql, array('idd' => $id));
$this->db->insert($table, $sql);}
}
$this->db->trans_complete();
if ($this->db->trans_status() === FALSE){print "Transaction Fails";return FALSE;}
return TRUE;
}
That function allows me to insert the data in this format only.
[[business] => Array
(
[title] => Email Marketing
[URL] => email-marketing
[category] => 3
[region] => 2
)
[description_] => Array
(
[text] => Some desc
)
[logo_] => Array
(
[blob] => mainlogo.png
)
]
as business, decription_, logo_ are db tables where title, URL, category, region, text, blob are the db columns to the corresponding tables and the rest is data that goes to those columns.
How I want it to works. For example in location_
I want to the array to change into my working format or something else that will work like this
location_ => ['text' => [[0] => 'Lemara Main Office'],
'priority' => [[0] => '1']
]
location_ => ['text' => [[1] => 'Themi Office'],
'priority' => [[1] => '2']
]
location_ => ['text' => [[2] => 'Sinoni Office'],
'priority' => [[2] => '3']
]
or like this
location_ => [0 => [['text' => 'Lemara Main Office'],
['priority' => '1']
],
1 => [['text' => 'Themi Main Office'],
['priority' => '2']
],
2 => [['text' => 'Sinoni Main Office'],
['priority' => '3']
]
],
And also support many columns not just the two.
Any help is deeply appreciated as I have been struggling for days to make this work. Thanks in advance.
I would suggest you convert your array to JSON String then insert it to DB as text.
JSON would handle your multidimentional data so well,
To convert your array to JSON : http://php.net/manual/en/function.json-encode.php
To convert your JSON to Array : http://php.net/manual/en/function.json-decode.php

eliminating duplicate values in multidimensional array

I was wondering what is the best way to eliminate duplicates within an array? Currently I'm running through a foreach loop to actually get this array, is there a way to say, if id already exists, don't insert into array?
foreach($categories2Sugg as $Category2Sugg)
{
$category_stringArray2Sugg[] = array("id"=>$Category2Sugg->id,"name"=>$Category2Sugg->name,"pluralName"=>$Category2Sugg->pluralName,"shortName"=>$Category2Sugg->shortName);
}
Array
(
[0] => Array
(
[id] => 4bf58dd8d48988d16c941735
[name] => Burger Joint
[pluralName] => Burger Joints
[shortName] => Burgers
)
[1] => Array
(
[id] => 4bf58dd8d48988d16c941735
[name] => Burger Joint
[pluralName] => Burger Joints
[shortName] => Burgers
)
[2] => Array
(
[id] => 4bf58dd8d48988d16c941735
[name] => Burger Joint
[pluralName] => Burger Joints
[shortName] => Burgers
)
[3] => Array
(
[id] => 4bf58dd8d48988d14e941735
[name] => American Restaurant
[pluralName] => American Restaurants
[shortName] => American
)
)
Or maybe its easier to do another function if this array already exists, just delete some values to output a new array?
Thanks!
Try array_unique php function that will help.
Also Try
$unique = array_map('unserialize', array_unique(array_map('serialize', $array)));
echo "<pre>";
print_r($unique);
echo "</pre>";
Above code is tested.
Complete Tested Code
<?php
$array = array
(
'0' => array
(
'id' => '4bf58dd8d48988d16c941735',
'name' => 'Burger Joint',
'pluralName' => 'Burger Joints',
'shortName' => 'Burgers'
),
'1' => array
(
'id' => '4bf58dd8d48988d16c941735',
'name' => 'Burger Joint',
'pluralName' => 'Burger Joints',
'shortName' => 'Burgers'
),
'2' => array
(
'id' => '4bf58dd8d48988d16c941735',
'name' => 'Burger Joint',
'pluralName' => 'Burger Joints',
'shortName' => 'Burgers'
),
'3' => array
(
'id' => '4bf58dd8d48988d14e941735',
'name' => 'American Restaurant',
'pluralName' => 'American Restaurants',
'shortName' => 'American'
)
);
$unique = array_map('unserialize', array_unique(array_map('serialize', $array)));
echo "<pre>";
print_r($unique);
?>
Cheers.

Compact multidimensional Array

i've a similar array:
Array
(
[0] => Array
(
[id] => 1
[name] => Mario
[type] => Doctor
[operations] => brain
[balance] => 3.00
)
[1] => Array
(
[id] => 3
[name] => Luca
[type] => Doctor
[operations] => hearth
[balance] => 6.00
)
[2] => Array
(
[id] => 3
[name] => Luca
[type] => Doctor
[operations] => hands
[balance] => 4.00
)
[3] => Array
(
[id] => 3
[name] => Luca
[type] => Doctor
[operations] => foots
[balance] => 1.00
)
)
I must to merge it for id, so obtain only 2 elements for array (0 and 1) and Luca (id 3) must be unified for operations, in a new array, similar to this, so in future print more clearly operations unified and not divided.
[...]
)
[1] => Array
(
[id] => 3
[name] => luca
[type] => doctore
[operations] => Array (6.00 hearts,
4.00 hands,
1.00 foots)
)
I can not figure how solve my trouble... Someone could help me please? Thank you very much to all!
<?php
$input = array(
array('id' => 1, 'name' => 'Mario', 'type' => 'Doctor', 'operations' => 'brain', 'balance' => 3.00),
array('id' => 3, 'name' => 'Luca', 'type' => 'Doctor', 'operations' => 'hearth', 'balance' => 6.00),
array('id' => 3, 'name' => 'Luca', 'type' => 'Doctor', 'operations' => 'hands', 'balance' => 4.00),
array('id' => 3, 'name' => 'Luca', 'type' => 'Doctor', 'operations' => 'foots', 'balance' => 1.00),
);
$output = array();
foreach ($input as $person)
{
// Add the person to the output, if needed.
if (array_key_exists($person['id'], $output) === false)
{
$output[$person['id']] =
array(
'id' => $person['id'],
'name' => $person['name'],
'type' => $person['type'],
'operations' => array(),
);
}
// Add the operation to the array of operations.
$output[$person['id']]['operations'][] =
array(
'type' => $person['operations'],
'balance' => $person['balance'],
));
}
foreach ($output as $person)
{
if (count($person['operations']) === 1)
{
// If the array contains only 1 item, pull it out of the array.
$output[$person['id']]['operations'] = $person['operations'][0];
}
}
print_r($output);

Sort Multidimentional Array in PHP according a part of an array

I have the following array:
items = array(
'note' => array(),
'text' => array(),
'year' => array()
)
So I have:
[note] => Array
(
[0] => 'note1'
[1] => 'note2'
[2] => 'note3'
),
[text] => Array
(
[0] => 'text1'
[1] => 'text2'
[2] => 'test3'
),
[year] => Array
(
[0] => '2002'
[1] => '2000'
[2] => '2011'
)
And I would like to arrange the above arrays by year. but when moving elements I would like to move the corresponding elements in other arrays(note,text).
For example:
[note] => Array
(
[2] => 'note3'
[0] => 'note1'
[1] => 'note2'
),
[text] => Array
(
[2] => 'text3'
[0] => 'text1'
[1] => 'test2'
),
[year] => Array
(
[2] => '2011'
[0] => '2002'
[1] => '2000'
)
I would first extract the year part and sort it by value, while still maintaining the key, using arsort():
$yearData = $array['year'];
arsort($yearData);//sort high-to-low by value, while maintain it's key.
Finally, sort the data using this newly sorted year:
$newArray['note'] = array();
$newArray['text'] = array();
$newArray['year'] = array();
foreach($yearData as $key => $value){
$newArray['note'][$key] = $array['note'][$key];
$newArray['text'][$key] = $array['text'][$key];
$newArray['year'][$key] = $array['year'][$key];
}
FYI, there are a bunch of functions that deal with sorting arrays in PHP.
I think a better organization to your array would be something like this:
[0] => Array(
'note' => note1, 'text' => 'text1', 'year' => '2002)
[1] => Array(
'note' => note2, 'text' => 'text2', 'year' => '2000)
[2] => Array(
'note' => note3, 'text' => 'text4', 'year' => '2011)
This way, each related item stays together and it's easier to sort them by the desired type.
$items = array(
array(
'note' => value,
'text' => value,
'year' => value
),
array(
'note' => value,
'text' => value,
'year' => value
)
)

Categories