PHP: How to get unique content from array? - php

I have a array and I need unique contents. How can I get rid of duplicates in this $tmparray:
array(176) {
[0]=>
array(2) {
[0]=>
string(22) "/ads/67006/didi"
[1]=>
string(73) "/Content/Pictures/Scaled/7b5c69572fdb1569ced695c278072ae0.jpg"
}
[1]=>
array(2) {
[0]=>
string(22) "/ads/67006/didi"
[1]=>
string(73) "/Content/Pictures/Scaled/7b5c69572fdb1569ced695c278072ae0.jpg"
}
[2]=>
array(2) {
[0]=>
string(22) "/ads/67006/didi"
[1]=>
string(73) "/Content/Pictures/Scaled/7b5c69572fdb1569ced695c278072ae0.jpg"
}
[3]=>
array(2) {
[0]=>
string(19) "/ads/67010/sylvesta"
[1]=>
string(73) "/Content/Pictures/Scaled/83ebba04b8eabd0458cc6dbbb85581da.jpg"
}
[4]=>
array(2) {
[0]=>
string(19) "/ads/67010/sylvesta"
[1]=>
string(73) "/Content/Pictures/Scaled/83ebba04b8eabd0458cc6dbbb85581da.jpg"
}
[5]=>
array(2) {
[0]=>
string(19) "/ads/67010/sylvesta"
[1]=>
string(73) "/Content/Pictures/Scaled/83ebba04b8eabd0458cc6dbbb85581da.jpg"
}
But I want it to look like: (Only unique contents.)
array(176) {
[0]=>
array(2) {
[0]=>
string(22) "/ads/67006/didi"
[1]=>
string(73) "/Content/Pictures/Scaled/7b5c69572fdb1569ced695c278072ae0.jpg"
}
[1]=>
array(2) {
[0]=>
string(19) "/ads/67010/sylvesta"
[1]=>
string(73) "/Content/Pictures/Scaled/83ebba04b8eabd0458cc6dbbb85581da.jpg"
}
}
I have tried with:
array_unique($tmparray);
array_unique can't do what I want. Anyone have a idea how to solve this?

your question seems duplicate of this
How to remove duplicate values from a multi-dimensional array in PHP
i guess array_map will solve your problem
$input = array_map("unserialize", array_unique(array_map("serialize", $input)));

You can use this code:
$newarray= array();
foreach ($tmparray as $value) {
if (!in_array($value,$newarray)) {
$newarray[ ] = $value;
}
}
var_dump($newarray);

I assume that by duplicate you mean two items where either elements are matching, since you are mapping ads to their pictures, therefore:
$target = array();
$elementCount = count($tmparray);
$newElementCount = 0;
for ($i = 0; $i < $elementCount; $i++) {
$found = false;
for ($j = 0; (!$found) && (j < $newElementCount); j++) {
$found = $target[$j][0] === $tmparray[$i][0] || $target[$j][1] === $tmparray[$i][1];
}
if (!$found) {
$target[$newElementCount++]=$tmparray[$i];
}
}

PHP array_unique is used only for single dimensional arrays, for multidimensional you can do this by serializing multidimensional array, like below
<?php
$dataArray = [
0=>["/ads/67006/didi","/Content/Pictures/Scaled/7b5c69572fdb1569ced695c278072ae0.jpg"],
1=>["/ads/67010/sylvesta","/Content/Pictures/Scaled/83ebba04b8eabd0458cc6dbbb85581da.jpg"],
2=>["/ads/67006/didi","/Content/Pictures/Scaled/7b5c69572fdb1569ced695c278072ae0.jpg"],
3=>["/ads/67010/sylvesta","/Content/Pictures/Scaled/83ebba04b8eabd0458cc6dbbb85581da.jpg"],
];
$serilaized = [];
$newArr = [];
### serilaize each node of multi array and create a new single dimention array..
foreach($dataArray as $val){
$serilaized[] = serialize($val);
}
### now perform array unique..
$serilaized_unique = array_unique($serilaized);
## unserialize each node of uniqur array..
foreach($serilaized_unique as $val){
$newArr[] = unserialize($val);
}
echo "<pre>";print_r($newArr);
?>
This will give you:
Array
(
[0] => Array
(
[0] => /ads/67006/didi
[1] => /Content/Pictures/Scaled/7b5c69572fdb1569ced695c278072ae0.jpg
)
[1] => Array
(
[0] => /ads/67010/sylvesta
[1] => /Content/Pictures/Scaled/83ebba04b8eabd0458cc6dbbb85581da.jpg
)
)
In short you can perform this in single line code with array_map
$dataArray = array_map('unserialize', array_unique(array_map('serialize', $dataArray)));

I got it working with this line:
$tmparray = array_unique($tmparray, SORT_REGULAR);

Related

How to group a multidimensional array by multiple subarray values?

I checked this question and answers:
How to group a multidimensional array by a particular subarray value?
He wanted to group results by 'level'. But how would you do it to group it by 'level' first and then by 'type'?
Its pretty straight forward. Loop through $items array. Get each item's level and type and if they are not set yet, initialize them with an empty array. Then just push the "cust" value into the array.
I have given the code below.
I am assuming "$items" is an array which contains the input.
$g = [];
foreach($items as $k => $v) {
$l = $v["level"];
$t = $v["type"];
$c = $v["cust"];
if(!isset($g[$l])) {
$g[$l] = [];
}
if(!isset($g[$l][$t])) {
$g[$l][$t] = [];
}
$g[$l][$t][] = [
"cust" => $c
];
}
var_dump($g);
The output of this code would be like below:
array(3) {
[1]=>
array(1) {
["standard"]=>
array(2) {
[0]=>
array(1) {
["cust"]=>
string(6) "XT8900"
}
[1]=>
array(1) {
["cust"]=>
string(6) "XT8944"
}
}
}
[3]=>
array(1) {
["premier"]=>
array(2) {
[0]=>
array(1) {
["cust"]=>
string(6) "XT8922"
}
[1]=>
array(1) {
["cust"]=>
string(6) "XT8816"
}
}
}
[7]=>
array(1) {
["standard"]=>
array(1) {
[0]=>
array(1) {
["cust"]=>
string(6) "XT7434"
}
}
}
}
[P.S.]: You can also use sort to solve this problem easily. That's another way of solving this problem.

Change the key of first arrays in three dimensional array in PHP

The following code gives the array below, however I need it formatted differently (stated after the array), so it will work for a javascript function I've already written.
$sql = "SELECT towhich, duedate, amount FROM sales WHERE email = '$email' ORDER BY duedate ASC";
$result = mysqli_query($conn, $sql);
$dbarray = array();
while($row = mysqli_fetch_assoc($result)) {
$dbarray[] = $row;
}
$graph = array();
$cnt = 0;
foreach($dbarray as $key => $values){
$orderdate = explode('-', $values['duedate']);
$month = $orderdate[1];
$graph[$month][$cnt] = array (
0 => $values['amount'],
1 => $values['towhich']
);
$cnt ++;
}
//Now it's grouped by date
Array output:
array(5)
{
["02"]=> array(2)
{
[0]=> array(2) { [0]=> string(2) "10" [1]=> string(9) "the co op" }
[1]=> array(2) { [0]=> string(2) "30" [1]=> string(9) "the co op" }
}
["03"]=> array(1)
{
[2]=> array(2) { [0]=> string(2) "50" [1]=> string(9) "the co op" }
}
["04"]=> array(1)
{
[3]=> array(2) {[0]=> string(2) "40" [1]=> string(9) "the co op" }
}
["05"]=> array(2)
{
[4]=> array(2) {[0]=> string(2) "10" [1]=> string(9) "the co op" }
[5]=> array(2) { [0]=> string(2) "10" [1]=> string(9) "the co op" }
}
["06"]=> array(1)
{
[6]=> array(2) { [0]=> string(2) "10" [1]=> string(9) "the co op" }
}
}
The key index value for array should not be, for example, ['02'], but, being the first in the containing array, [0], like normal; and '03' should be [1].
I've looked around a lot, indeed it helped with what bit of code I've produced, however all answers seem to deal with changing the key value further inside the large array. I'm new with multidimensional arrays, btw. Thanks in advance.
In case you're wondering why I've done it like so, so far, it's because each first array should correspond to a different month; that's why I've ordered by date and all that.
If I got you right, you can use: array_values :
$graph = array_values($graph);
so "02" will be 0, "03" will be 1 , ... etc.
$key in your foreach will be the relative record number that the row occurs in the query.
$graph = array();
$cnt = 0;
foreach($dbarray as $key => $values){
$orderdate = explode('-', $values['duedate']);
$month = $orderdate[1];
$graph[$month][$cnt] = array (
$graph[$key] = array (
$month,
$values['amount'],
$values['towhich']
);
$cnt ++;
}

PHP Arrays - Merge two arrays where a value is added together

I need some more help regarding PHP Arrays and the issue I am having. I have an array like this: -
array(2) {
[0]=>
array(2) {
[0]=>
array(2) {
["count"]=>
string(3) "100"
["id"]=>
int(46)
}
[1]=>
array(2) {
["count"]=>
string(3) "300"
["id"]=>
int(53)
}
}
[1]=>
array(1) {
[0]=>
array(2) {
["count"]=>
string(3) "200"
["id"]=>
int(46)
}
}
}
However, I would like it to look more like this as array: -
array(2) {
[0]=>
array(2) {
["count"]=>
string(3) "300" <--- This has been added from Array 1 and 2
["id"]=>
int(46)
}
[1]=>
array(2) {
["count"]=>
string(3) "300"
["id"]=>
int(53)
}
}
Basically if the same id is in both areas I want the count number to be added to each other but if it's not then it needs to just be left alone and included in the array.
I have used a number of array functions such as array_merge and array_push but I am running out of ideas of how this could work. I have also started working on a foreach with if statements but I just got myself completely confused. I just need a second pair of eyes to look at the issue and see howe it can be done.
Thanks again everyone.
Should work with something like this:
$idToCountArray = array(); //temporary array to store id => countSum
array_walk_recursive($inputArray, function($value,$key) { //walk each array in data structure
if(isset(value['id']) && isset($value['count'])) {
//we have found an entry with id and count:
if(!isset($idToCountArray[$value['id']])) {
//first count for id => create initial count
$idToCountArray[$value['id']] = intval($value['count']);
} else {
//n'th count for id => add count to sum
$idToCountArray[$value['id']] += intval($value['count']);
}
}
});
//build final structure:
$result = array();
foreach($idToCountArray as $id => $countSum) {
$result[] = array('id' => $id, 'count' => ''.$countSum);
}
Please note that I have not testet the code and there is probably a more elegant/performant solution.
You could use something like this:
$end_array = array();
function build_end_array($item, $key){
global $end_array;
if (is_array($item)){
if( isset($item["id"])){
if(isset($end_array[$item["id"]]))
$end_array[$item["id"]] = $end_array[$item["id"]] + $item["count"]*1;
else
$end_array[$item["id"]] = $item["count"]*1;
}
else {
array_walk($item, 'build_end_array');
}
}
}
array_walk($start_array, 'build_end_array');
Here is a fiddle.
Thank you ever so much everyone. I actually worked it by doing this: -
$fullArray = array_merge($live, $archive);
$array = array();
foreach($fullArray as $key=>$value) {
$id = $value['id'];
$array[$id][] = $value['count'];
}
$result = array();
foreach($array as $key=>$value) {
$result[] = array('id' => $key, 'count' => array_sum($value));
}
return $result;

PHP rewrap array to summarize it

I got the following array:
["positive"]=>
array(3) {
[0]=>
array(2) {
[0]=>
int(1473022800000) //unix timestamp
[1]=>
int(100)
}
[1]=>
array(2) {
[0]=>
int(1473109200000)
[1]=>
int(200)
}
[2]=>
array(2) {
[0]=>
int(1473195600000)
[1]=>
int(300)
}// etc...
["neutral"]=>
array(3) {
[0]=>
array(2) {
[0]=>
int(1473022800000) //same day as with positive
[1]=>
int(400)
}
[1]=>
array(2) {
[0]=>
int(1473109200000)//also second same day as with positive
[1]=>
int(500)
}
[2]=>
array(2) {
[0]=>
int(1473195600000)
[1]=>
int(600)
} // etc...
I need to rewrap it to get the following:
["1473022800000"]=>
array(2) {
['positive']=> (int)500 //example values, should be calculated
['neutral'] => (int)200
}
["1473109200000"]=>
array(2) {
['positive']=> (int)500
['neutral'] => (int)200
}
So I need to rewrap it to got not from positives or neutrals but from dates in order to sum it up this way. Any suggestions how to do that with PHP would be welcome. Thank you.
UPD Here is what I have tried so far
foreach($myarray as $key=>$val){ //getting the dates
//var_dump($key);exit;
for($i=0;$i<=30;++$i){
$dates[] = $val[$i][0];
}
}
$dates = array_unique(array_values($dates));
$dates_upd = [];
foreach($dates as $date) {
foreach($myarray as $key=>$val){
for($i=0;$i<=30;++$i){
if($val[$i][0]==$date){
$dates_upd['date'] = $date;
$dates_upd['date']['total'] = $val[$i][1];//getting errors here (cant use a scalar value etc...)
}
}
}
}
You can do this with a couple of nested foreach loops:
$out=[];
foreach($myarray as $key=>$subarray){
foreach($subarray as $item){
$date = $item[0];
$value = $item[1];
$out[$date][$key]=$value;
}
}

How to find the lowest number in an Associative Array

This is the problem:
I have the following array (from $wpdb->get_results()):
array(6) {
[0]=> array(1) {
[0]=> string(7) "1102006"
}
[1]=> array(1) {
[0]=> string(7) "1102006"
}
[2]=> array(1) {
[0]=> string(7) "8092007"
}
[3]=> array(1) {
[0]=> string(8) "23062012"
}
[4]=> array(1) {
[0]=> string(8) "29072000"
}
[5]=> array(1) {
[0]=> string(8) "30082008"
}
}
And I would like to find the lowest integer from 10,000 on that is NOT in this array. In this case the answer would be 10,000 as 10,000 is not in the array.
Thanks
This is how I interpreted your question.
Starting from 10000, find the first available number that is NOT within your data array.
<?php
$data = array(
array('1102006'),
array('1102006'),
array('8092007'),
array('23062012'),
array('29072000'),
array('30082008')
);
// flatten the array to a single dimension
function flatten(&$v) { $v = $v[0]; }
array_walk($data, 'flatten');
// minimum number
$num = 10000;
// while a value has not been found
while (!isset($value))
{
// check if the current number is in our data (exclusion list)
if (array_search($num, $data) === false)
$value = $num;
// increment for our next search
$num++;
}
echo $value;
If you are just after the minimum value in that array, flatten the array in the previous answer and use min:
echo min($data);

Categories