How can I remove duplicates in an array like this? - php

How can i remove duplicates in an array like this?
My array $test1 gives me this out:
Array (
[0] => Array ( [id] => 47523 [date] => 12-02-13 14:36:32 )
[1] => Array ( [id] => 47523 [date] => 12-02-13 13:56:48 )
[2] => Array ( [id] => 38639 [date] => 12-02-13 13:38:51 )
[3] => Array ( [id] => 38639 [date] => 12-02-13 13:07:43 )
)
My array $test2 gives me this out:
Array (
[0] => Array ( [id] => 47523 [date] => 12-02-13 14:36:32 )
[1] => Array ( [id] => 47523 [date] => 12-02-13 13:56:48 )
[2] => Array ( [id] => 38639 [date] => 12-02-13 13:38:51 )
[3] => Array ( [id] => 38639 [date] => 12-02-13 13:07:43 )
[4] => Array ( [id] => 53241 [date] => 12-02-13 11:02:48 )
)
But I want the output to be that way with the latest date
Array (
[0] => Array ( [id] => 53241 [date] => 03-02-13 11:02:48 )
)
What can i do?

$test1 = array (
array ( "id" => 47523, "date" => "12-02-13 14:36:32" ),
array ( "id" => 47523, "date" => "12-02-13 13:56:48" ),
array ( "id" => 38639, "date" => "12-02-13 13:38:51" ),
array ( "id" => 38639, "date" => "12-02-13 13:07:43" )
);
$test2 = array (
array ( "id" => 47523, "date" => "12-02-13 14:36:32" ),
array ( "id" => 47523, "date" => "12-02-13 13:56:48" ),
array ( "id" => 38639, "date" => "12-02-13 13:38:51" ),
array ( "id" => 38639, "date" => "12-02-13 13:07:43" ),
array ( "id" => 53241, "date" => "12-02-13 11:02:48" )
);
foreach($test2 as $array) {
if (!in_array($array, $test1)) {
$new[] = $array;
}
}
print_r($new);

First merge the 2 arrays (from $test2 into $tes1 in this case):
foreach($test2 as $id=>$arr){
$test1[] = $arr;
}
Then sort the $test1 by date (putting the oldest dates last, and newest dates first):
foreach ($test1 as $key => $row) {
$orderByDate[$key] = strtotime($row['date']);
}
array_multisort($orderByDate, SORT_DESC, $dataArray);
Then remove the duplicates (This will keep the newest datetime and remove earlier ones)
$unique = array()
foreach($test1 as $id => $arr){
if( in_array($arr->id, $unique ) {
unset($test1[$id]);
}
else {
array_push($unique, $arr->id);
}
}

Try using array_unique($test1)

You can use array_intersect_key with array_unique and array_map for single line job:
In PHP >5.3.0:
$array = array (
0 => array ( "id" => 47523, "date" => "12-02-13 14:36:32" ),
1 => array ( "id" => 47523, "date" => "12-02-13 13:56:48" ),
2 => array ( "id" => 38639, "date" => "12-02-13 13:38:51" ),
3 => array ( "id" => 38639, "date" => "12-02-13 13:07:43" )
);
$array = array_intersect_key($array, array_unique(array_map(function($n){ return $n['id']; }, $array)));
print_r($array);
PHP <5.3.0
$array = array (
0 => array ( "id" => 47523, "date" => "12-02-13 14:36:32" ),
1 => array ( "id" => 47523, "date" => "12-02-13 13:56:48" ),
2 => array ( "id" => 38639, "date" => "12-02-13 13:38:51" ),
3 => array ( "id" => 38639, "date" => "12-02-13 13:07:43" )
);
function mapArray($n){
return $n['id'];
}
$array = array_intersect_key($array, array_unique(array_map("mapArray", $array)));
print_r($array);

You should write your own function beacuse array_unique is not for multidimensional arrays.
function array_unique_md($array)
{
$temp = array();
foreach($array as $key => $value)
{
if(!isset($temp[$value['id']])) $temp[$value['id']] = $value['date'];
}
$your_structure = array();
foreach($temp as $key=> $value)
{
$your_structure[] = array('id'=>$key,'date'=>$value);
}
return $your_structure;
}

You can use array_reduce
$data = array_reduce($data, function($a,$b){
isset($a[$b['id']]) or $a[$b['id']] = $b;
return $a;
});
var_dump(array_values($data));
See Live Demo

Related

Make associative array of unique values from column containing arrays

Array
(
[0] => Array
(
[id] => 21153
[genre] => ["History","Drama", "Thriller"]
)
[1] => Array
(
[id] => 21152
[genre] => ["ACTION"]
)
[2] => Array
(
[id] => 21151
[genre] => ["ROMANTIC"]
)
[3] => Array
(
[id] => 21150
[genre] => ["Drama"]
)
)
I have with the above array and I want to convert that array to an unique array as mentioned below, and there should be any duplicate values.
Array(
[History] => "History"
[ACTION] => "ACTION"
[ROMANTIC] => "ROMANTIC"
[Drama] => "Drama"
[Thriller]=>"Thriller"
)
I don't really get how the resulting array makes any sense, but here you are:
Loop through the array, loop through the genres and push items to a new array.
<?
$a = Array
(
[
"id" => 21153,
"genre" => ["History","Drama", "Thriller"]
],
[
"id" => 21152,
"genre" => ["ACTION"]
]
);
$result = [];
foreach($a as $b) {
foreach($b['genre'] as $genre) {
$result[$genre] = $genre; // don't need to check if it exists already, because we'll overwrite it anyway.
}
}
echo "<pre>";
print_r($result);
echo "</pre>";
// output:
Array
(
[History] => History
[Drama] => Drama
[Thriller] => Thriller
[ACTION] => ACTION
)
It can be done by using foreach() loop and in_array() function like below
$myArray=array();
$array = array(
array("id"=>21153,"genre"=>array("History","Drama", "Thriller")),
array("id"=>21152,"genre"=>array("ACTION")),
array("id"=>21151,"genre"=>array("ROMANTIC")),
array("id"=>21150,"genre"=>array("Drama"))
);
foreach($array as $arr){
foreach($arr as $genres){
if(is_array($genres)){
foreach($genres as $elem){
if (!in_array($elem, $myArray))
{
$myArray[$elem]=$elem;
}
}
}
}
}
print_r($myArray);
This is a function that resolves what you ask, though I'm not sure it is quite useful to have value and key being identical. I'm just looping over all genders and add only the ones I don't already have store in returning array. probably a bit dangerous with your code because it is case sensitive
function getGenders(array $rawValues) :array {
$distinctGenders = [];
foreach ($rawValues as $row) {
foreach ($row["genre"] as $gender) {
if (!in_array($gender, $distinctGenders)) {
$distinctGenders[$gender] = $gender;
}
}
}
return $distinctGenders;
}
By doing the changes, I have fixed this,
$responseData = Array(
[0] => Array
(
[id] => 21153
[genre] => ["History","Drama", "Thriller"]
)
[1] => Array
(
[id] => 21152
[genre] => ["ACTION"]
)
[2] => Array
(
[id] => 21151
[genre] => ["ROMANTIC"]
)
[3] => Array
(
[id] => 21150
[genre] => ["Drama"]
)
foreach ($responseData as $data){
$strReplace = str_replace(array('[',']') , '' , $data['genre']);
$explodeData[] = explode(',', $strReplace);
}
And the output after exploding is :
$explodeData = Array
(
[0] => Array
(
[0] => "History"
[1] => "Drama"
[2] => "Thriller"
)
[1] => Array
(
[0] => "ACTION"
)
[2] => Array
(
[0] => "ROMANTIC"
)
[3] => Array
(
[0] => "Drama"
)
)
And finally by the foreach loop :
foreach ($explodeData as $arr) {
foreach ($arr as $genres) {
if (!in_array($genres, $myArray)) {
$myArray[$genres] = $genres;
}
}
}
And finally the required output comes as below :
Array(
["History"] => "History"
["Drama"] => "Drama"
["Thriller"] => "Thriller"
["ACTION"] => "ACTION"
["ROMANTIC"] => "ROMANTIC"
)
Flatten the column of data.
Assign keys from the values (this ensures uniqueness).
Code: (Demo)
$array = [
["id" => 21153, "genre" => ["History", "Drama", "Thriller"]],
["id" => 21152, "genre" => ["ACTION"]],
["id" => 21151, "genre" => ["ROMANTIC"]],
["id" => 21150, "genre" => ["Drama"]]
];
$flat = array_merge(...array_column($array, 'genre'));
var_export(
array_combine($flat, $flat)
);
Output:
array (
'History' => 'History',
'Drama' => 'Drama',
'Thriller' => 'Thriller',
'ACTION' => 'ACTION',
'ROMANTIC' => 'ROMANTIC',
)

how to generate multidimensional array from array value

i'm new in php and i stuck some where actually i need to generate multidimensional array from array value.
e.g my array is like that and remember all array and value are dynamic
array(
0 => array(
0 => "college"
1 => "student"
2 => "contact"
),
1 => array(
0 => "college"
1 => "parents"
2 => "contact"
),
2 => array(
0 => "school"
1 => "parents"
2 => "contact"
),
3 => array(
0 => "school"
1 => "student"
2 => "contact"
))
and i want result like that
0 => array (
"college" => array(
"student" => array (
"contact" => array (
"address" => "address_value"
)
),
"parents" => array (
"contact" => array (
"address" => "address_value"
)
),
),
"school" => array(
"student" => array (
"contact" => array (
"address" => "address_value"
)
),
"parents" => array (
"contact" => array (
"address" => "address_value"
)
),
)),
i want to generate multidimensional array till the array value and last array has some value
can any one help me with standard way.
help will appreciated..
thanks in advance
Try this:
<?php
function group($a, $level, $previous = '') {
$b = [];
for( $i = 0, $n = count($a); $i < $n; ++$i ) {
if( $level > 0 && $a[$i][$level-1] !== $previous ) {
continue;
}
$key = $a[$i][$level];
$b[$key] = [];
if( array_key_exists($level+1, $a[$i]) ) {
$b[$key] = group($a, $level+1, $key);
}
}
return $b;
}
print_r(group($a, 0));
Output:
Array(
[college] => Array (
[student] => Array (
[contact] => Array ()
)
[parents] => Array (
[contact] => Array ()
)
)
[school] => Array (
[student] => Array (
[contact] => Array ()
)
[parents] => Array (
[contact] => Array ()
)
)
)
Using #AlivetoDie example:
Array (
[college] => Array (
[student] => Array (
[contact] => Array ()
)
[parents] => Array (
[contact] => Array ()
)
)
[school] => Array (
[parents] => Array (
[contact] => Array ()
)
[student] => Array (
[contact] => Array ()
)
[data] => Array (
[contact] => Array()
)
)
)

Store column data from a multidimensional array while preserving missing elements

I have an array ($myArray) which looks like
Array ( [0] =>
Array ( [0] =>
Array (
[Date] => 1776-08-08
[Color] => Yellow
[Description] => Rotten
) )
[1] => Array ( )
[2] =>
Array ([0] =>
Array (
[Date] => 2018-05-13
[Color] => Red
[Status] => Fresh
)
[1] =>
Array (
[Date] => 1991-03-29
[Color] => Green
[Status] => Fresh ) )
I loop though the content for the values of Date using
array_walk_recursive($myArray, function($v, $k){
if ($k == "Date") echo $v . PHP_EOL;
This would get me the correct output.
1776-08-08 2018-05-13 1991-03-29
I want to add the output into an array and even if the value is null (ie[1] above) to still set an empty array.
For example $newArray =
Array ( [0] => 1776-08-08 )
Array ( )
Array ( [0] => 2018-05-13 [1] => 1991-03-29 )
Given your example, an option is to use array_column() on each of the items in the outermost array, which is easy with the array_map() function.
$input = array(
array(
array(
"Date" => "1776-08-08",
"Color" => "Yellow",
"Description" => "Rotten",
),
),
array(
),
array(
array(
"Date" => "2018-05-13",
"Color" => "Red",
"Status" => "Fresh",
),
array(
"Date" => "1991-03-29",
"Color" => "Green",
"Status" => "Fresh",
),
),
);
$output = array_map(function($sub_arrays) {
return array_column($sub_arrays, "Date");
}, $input);
print_r($output);
The above will output something like:
Array
(
[0] => Array
(
[0] => 1776-08-08
)
[1] => Array
(
)
[2] => Array
(
[0] => 2018-05-13
[1] => 1991-03-29
)
)
You'll need to do a normal foreach loop for the top-level, and then use array_walk_recursive for the nested arrays.
$newArray = array();
foreach ($myArray as $el) {
$temp = array();
array_walk_recursive($el, function($v, $k) use (&$temp) {
if ($k == "Date") {
$temp[] = $v;
}
});
$newArray[] = $temp;
}
DEMO

how to merge array when the value is same

I have two arrays like this:
array1 = Array (
[0] => Array ( [value] => 1 [date] => 2014-03-15 ),
[1] => Array ( [value] => 1 [date] => 2014-03-15 )
);
array2 = Array (
[0] => Array ( [value] => 1 [date] => 2014-03-15 ),
[1] => Array ( [value] => 1 [date] => 2014-03-16 )
);
How to get output like this?
date 2014-03-15 = 3
date 2014-03-16 = 1
You can not merge those array directly with array_merge, because the counting based on 'value', so you must create some codes, try this:
$array1 = array(
array("value" => 1, "date" => "2014-03-15"),
array("value" => 1, "date" => "2014-03-15"),
);
$array2 = array(
array("value" => 1, "date" => "2014-03-15"),
array("value" => 1, "date" => "2014-03-16"),
);
foreach(array_merge($array1, $array2) as $arr){
!isset($array[$arr['date']]) ? $array[$arr['date']] = $arr['value'] : $array[$arr['date']] += $arr['value'];
}
print_r($array);
it will returns :
Array ( [2014-03-15] => 3 [2014-03-16] => 1 )

getting sub array from the given array in php

I have a array variable $data which has the following array structure:
Array
(
[0] => Array
(
[rowdata] => Array
(
[0] => Array
(
[wiecont_03] =>
[tevrc_04] =>
[opmerkTXT] => Overall NPS
[0] => Array-----------------------
( |
[0] => rapport |
[1] => npsorg |
[3] => npsdetbe | i want this
part of the array
)-------------------------------
)
[1] => Array
(
[DOELGROEP] => 2
[KANTOOR] => 2
[OBLIGOCATEGORIE] => 3
[NAAM] => dfdf
[WEIGHT] => 0.95
[opmerkTXT] => Overall NPS
[0] => Array
(
[1] => npsorg
[3] => npsdetbe
)
)
)
[reason] => column values are not correct
)
)
from the above array structure i want to fetch the sub array if any as depicted by the dotted line.
Desired Output:
[0] => Array
(
[0] => rapport
[1] => npsorg
[3] => npsdetbe
)
and
[0] => Array
(
[1] => npsorg
[3] => npsdetbe
)
What i have tried: i tried array_slice() and array_chunks() but none of them worked in my case.
Thanks in advance
You also can do it(in short) like this:
Demo: https://eval.in/86588
<?php
$arr = array
(
0 => array
(
"rowdata" => array
(
"0" => array
(
"wiecont_03" => "",
"tevrc_04" => "",
"opmerkTXT" => "Overall NPS",
"0" => array
(
"0" => "rapport",
"1" => "npsorg",
"3" => "npsdetbe"
)
),
"1" => array
(
"DOELGROEP" => 2,
"KANTOOR" => 2,
"OBLIGOCATEGORIE" => 3,
"NAAM" => "dfdf",
"WEIGHT" => 0.95,
"opmerkTXT" => "Overall NPS",
"0" => array
(
"1" => "npsorg",
"3" => "npsdetbe",
)
)
)
)
);
$re = array();
//print_r($arr[0]['row_data']);
$i=0;
foreach($arr[$i]['rowdata'] as $a){
if(is_array($a[0])){
array_push($re,$a[0]);
}
$i =$i+1;
}
print_r($re);
TRY THIS:
Demo : https://eval.in/86560
$arr = array
(
"0" => array
(
"rowdata" => array
(
"0" => array
(
"wiecont_03" => "",
"tevrc_04" => "",
"opmerkTXT" => "Overall NPS",
"0" => array
(
"0" => "rapport",
"1" => "npsorg",
"3" => "npsdetbe"
)
),
"1" => array
(
"DOELGROEP" => 2,
"KANTOOR" => 2,
"OBLIGOCATEGORIE" => 3,
"NAAM" => "dfdf",
"WEIGHT" => 0.95,
"opmerkTXT" => "Overall NPS",
"0" => array
(
"1" => "npsorg",
"3" => "npsdetbe",
)
)
)
)
);
$re = array();
foreach($arr as $a){
foreach($a as $b){
foreach($b as $c){
array_push($re,$c[0]);
}
}
}
print_r($re);
OUTPUT
Array
(
[0] => Array
(
[0] => rapport
[1] => npsorg
[3] => npsdetbe
)
[1] => Array
(
[1] => npsorg
[3] => npsdetbe
)
)
Your pattern is same in all case then this function is fine
function getMyArray($array){
$rowdata = $array[0]['rowdata'];
$resultArray = array();
foreach($rowdata as $val){
$resultArray[] = $val[0];
}
return $resultArray;
}
Usage:-
$array = "YOUR ARRAY HERE";
$result = getMyArray($array);
foreach($data[0]['rowdata'] as $value){
print_r($value[0]);
}

Categories