PHP Count Duplicate Total Link - php

how can i count the total duplicate link in the array?
its similar question here: count of duplicate elements in an array in php
but im not sure how to implement the code on my case.
my server PHP version 5.4
Array
(
[0] => Array
(
[link] => http://myexample.com
[total] => 3
)
[1] => Array
(
[link] => http://myexampledomain.com
[total] => 2
)
[2] => Array
(
[link] => http://myexample.com
[total] => 1
)
)
I am expecting the result to be:
http://myexample.com: 4
http://myotherdomain.com: 2

You can simply use
$result = [];
array_walk($arr, function($v, $k)use(&$result) {
if (isset($result[$v['link']])) {
$result[$v['link']] += $v['total'];
}else{
$result[$v['link']] = $v['total'];
}
});
print_r($result);
Demo

Try below code:
<?php
$array = array(array("link" => "http://myexample.com", "total" => 3), array("link" => "http://myexampledomain.com", "total" => 2), array("link" => "http://myexample.com", "total" => 1));
$res = array();
foreach ($array as $vals) {
if (array_key_exists($vals['link'], $res)) {
$res[$vals['link']]+=$vals['total'];
} else {
$res[$vals['link']]=$vals['total'];
}
}
print_r($res);
?>

You can use this simple logic :
$tempArray = array();
foreach ($array as $value) {
if (!array_key_exists($value['link'],$tempArray) {
$tempArray[$value['link']] = 1;
} else {
$tempArray[$value['link']] = $tempArray['link'] + 1;
}
}
print_r($tempArray);

Related

Explode array's data and make new array

I have this array:
Array
(
[0] => Array
(
[0] => 1
[1] => a,b,c
)
[1] => Array
(
[0] => 5
[1] => d,e,f
)
)
I want the final array to be this:
Array
(
[0] => Array
(
[0] => 1
[1] => a
)
[1] => Array
(
[0] => 1
[1] => b
)
[2] => Array
(
[0] => 1
[1] => c
)
[3] => Array
(
[0] => 5
[1] => d
)
[4] => Array
(
[0] => 5
[1] => e
)
[5] => Array
(
[0] => 5
[1] => f
)
)
This is what I did:
<?php
$array = array(array(1,"a,b,c"),array(5,"d,e,f"));
$temp=array();
$count = 0;
foreach($array as $arr){
$rows = explode(",",$arr[1]);
foreach($rows as $row){
$temp[$count] = $arr;
$temp[$count][1] = $row;
$count++;
}
}
print_r($temp);
?>
This totally works but I was wondering if there was a better way to do this. This can be very slow when I have huge data.
Try like this way...
<?php
$array = array(array(1,"a,b,c"),array(5,"d,e,f"));
$temp=array();
$count = 0;
foreach($array as $arr){
$rows = explode(",",$arr[1]);
foreach($rows as $row){
$temp[$count][] = $arr[0];
$temp[$count][] = $row;
$count++;
}
}
/*print "<pre>";
print_r($temp);
print "<pre>";*/
?>
Here's a functional approach:
$result = array_merge(...array_map(function(array $a) {
return array_map(function($x) use ($a) {
return [$a[0], $x];
}, explode(",", $a[1]));
}, $array));
Try it online.
Or simply with two loops:
$result = [];
foreach ($array as $a) {
foreach (explode(",", $a[1]) as $x) {
$result[] = [$a[0], $x];
}
}
Try it online.
Timing these reveals that a simple loop construct is ~8 times faster.
functional: 4.06s user 0.08s system 99% cpu 4.160 total
loop: 0.53s user 0.05s system 102% cpu 0.561 total
If you need other way around,
$array = array(array(1, "a,b,c"), array(5, "d,e,f"));
$temp = [];
array_walk($array, function ($item, $key) use (&$temp) {
$second = explode(',', $item[1]);
foreach ($second as $v) {
$temp[] = [$item[0], $v];
}
});
print_r($temp);
array_walk — Apply a user supplied function to every member of an array
Here is working demo.

How can I compare two Arrays and detect if the values are incorrect or missing?

I have to arrays I would like to compare:
$original and $duplicate.
for example here is my original file:
print_r($original);
Array ( [0] => cat423 [1] => dog456 [2] => horse872 [3] => duck082 )
and here is my duplicate:
print_r($dublicate);
Array ( [0] => cat423 [1] => dug356 )
I compare them with array_diff:
$result = array_diff($original, $dublicate);
My result:
Array ( [1] => dog456 [2] => horse872 [3] => duck082 )
So far so good, but I need to make a difference between the values which are incorrect and the values which are completely missing. Is this possible?
A way would be to crawl the entire original array, afterwards you will have two arrays, missings and duplicates.
$original = array("cat423", "dog456", "horse872", "duck082");
$duplicate = array("cat423", "dug356");
$missings = $duplicates = array();
foreach ($original as $val) {
if (in_array($val, $duplicate))
$duplicates[] = $val;
else
$missings[] = $val;
}
If you need the keys as well, you would have to alter the foreach loop like so:
foreach ($original as $key=>$val) {
if (in_array($val, $duplicate))
$duplicates[] = array("key" => $key, "value" => $val);
else
$missings[] = array("key" => $key, "value" => $val);
}
use in_array function
$original = array("cat423", "dog456", "horse872", "duck082");
$duplicate = array("cat423", "dug356");
foreach ($original as $item) {
if(in_array($item, $duplicate))
{
$dup[] = $item;
}
else
{
$miss[] = $item;
}
}
print_r($miss); #Array ( [0] => dog456 [1] => horse872 [2] => duck082 )
print_r($dup); #Array ( [0] => cat423 )
Working Preview

Associative index array to associative associative array

Problem
I have an array which is returned from PHPExcel via the following
<?php
require_once 'PHPExcel/Classes/PHPExcel/IOFactory.php';
$excelFile = "excel/1240.xlsx";
$objReader = PHPExcel_IOFactory::createReader('Excel2007');
$objPHPExcel = $objReader->load($excelFile);
foreach ($objPHPExcel->getWorksheetIterator() as $worksheet) {
$arrayData[$worksheet->getTitle()] = $worksheet->toArray();
}
print_r($arrayData);
?>
This returns:
Array
(
[Films] => Array
(
[0] => Array
(
[0] => Name
[1] => Rating
)
[1] => Array
(
[0] => Shawshank Redemption
[1] => 39
)
[2] => Array
(
[0] => A Clockwork Orange
[1] => 39
)
)
[Games] => Array
(
[0] => Array
(
[0] => Name
[1] => Rating
)
[1] => Array
(
[0] => F.E.A.R
[1] => 4
)
[2] => Array
(
[0] => World of Warcraft
[1] => 6
)
)
)
What I would like to have is
Array
(
[Films] => Array
(
[0] => Array
(
[Name] => Shawshank Redemption
[Rating] => 39
)
[1] => Array
(
[Name] => A Clockwork Orange
[Rating] => 39
)
)
[Games] => Array
(
[0] => Array
(
[Name] => F.E.A.R
[Rating] => 4
)
[1] => Array
(
[Name] => World of Warcraft
[Rating] => 6
)
)
)
The arrays names (Films, Games) are taken from the sheet name so the amount can be variable. The first sub-array will always contain the key names e.g. Films[0] and Games[0] and the amount of these can be varible. I (think I) know I will need to do something like below but I'm at a loss.
foreach ($arrayData as $value) {
foreach ($value as $rowKey => $rowValue) {
for ($i=0; $i <count($value) ; $i++) {
# code to add NAME[n] as keys
}
}
}
I have searched extensively here and else where if it is a duplicate I will remove it.
Thanks for any input
Try
$result= array();
foreach($arr as $key=>$value){
$keys = array_slice($value,0,1);
$values = array_slice($value,1);
foreach($values as $val){
$result[$key][] = array_combine($keys[0],$val);
}
}
See demo here
You may use nested array_map calls. Somehow like this:
$result = array_map(
function ($subarr) {
$names = array_shift($subarr);
return array_map(
function ($el) use ($names) {
return array_combine($names, $el);
},
$subarr
);
},
$array
);
Demo
Something like this should work:
$newArray = array();
foreach ($arrayData as $section => $list) {
$newArray[$section] = array();
$count = count($list);
for ($x = 1; $x < $count; $x++) {
$newArray[$section][] = array_combine($list[0], $list[$x]);
}
}
unset($arrayData, $section, $x);
Demo: http://ideone.com/ZmnFMM
Probably a little late answer, but it looks more like your tried solution
//Films,Games // Row Data
foreach ($arrayData as $type => $value)
{
$key1 = $value[0][0]; // Get the Name Key
$key2 = $value[0][1]; // Get the Rating Key
$count = count($value) - 1;
for ($i = 0; $i < $count; $i++)
{
/* Get the values from the i+1 row and put it in the ith row, with a set key */
$arrayData[$type][$i] = array(
$key1 => $value[$i + 1][0],
$key2 => $value[$i + 1][1],
);
}
unset($arrayData[$type][$count]); // Unset the last row since this will be repeated data
}
I think this will do:
foreach($arrayData as $key => $array){
for($i=0; $i<count($array[0]); $i++){
$indexes[$i]=$array[0][$i];
}
for($i=1; $i<count($array); $i++){
for($j=0; $j<count($array[$i]); $j++){
$temp_array[$indexes[$j]]=$array[$i][$j];
}
$new_array[$key][]=$temp_array;
}
}
print_r($new_array);
EDIT: tested and updated the code, works...

count of duplicate elements in an array in php

Hi,
How can we find the count of duplicate elements in a multidimensional array ?
I have an array like this
Array
(
[0] => Array
(
[lid] => 192
[lname] => sdsss
)
[1] => Array
(
[lid] => 202
[lname] => testing
)
[2] => Array
(
[lid] => 192
[lname] => sdsss
)
[3] => Array
(
[lid] => 202
[lname] => testing
)
)
How to find the count of each elements ?
i.e, count of entries with id 192,202 etc
You can adopt this trick; map each item of the array (which is an array itself) to its respective ['lid'] member and then use array_count_value() to do the counting for you.
array_count_values(array_map(function($item) {
return $item['lid'];
}, $arr);
Plus, it's a one-liner, thus adding to elite hacker status.
Update
Since 5.5 you can shorten it to:
array_count_values(array_column($arr, 'lid'));
foreach ($array as $value)
{
$numbers[$value[lid]]++;
}
foreach ($numbers as $key => $value)
{
echo 'numbers of '.$key.' equal '.$value.'<br/>';
}
Following code will count duplicate element of an array.Please review it and try this code
$arrayChars=array("green","red","yellow","green","red","yellow","green");
$arrLength=count($arrayChars);
$elementCount=array();
for($i=0;$i<$arrLength-1;$i++)
{
$key=$arrayChars[$i];
if($elementCount[$key]>=1)
{
$elementCount[$key]++;
} else {
$elementCount[$key]=1;
}
}
echo "<pre>";
print_r($elementCount);
OUTPUT:
Array
(
[green] => 3
[red] => 2
[yellow] => 2
)
You can also view similar questions with array handling on following link
http://solvemyquest.com/count-duplicant-element-array-php-without-using-built-function/
The following code will get the counts for all of them - anything > 1 at the end will be repeated.
<?php
$lidCount = array();
$lnameCount = array();
foreach ($yourArray as $arr) {
if (isset($lidCount[$arr['lid']])) {
$lidCount[$arr['lid']]++;
} else {
$lidCount[$arr['lid']] = 1;
}
if (isset($lnameCount [$arr['lname']])) {
$lnameCount [$arr['lname']]++;
} else {
$lnameCount [$arr['lname']] = 1;
}
}
$array = array('192', '202', '192', '202');
print_r(array_count_values($array));
$orders = array(
array(
'lid' => '',
'lname' => '',
))....
$foundIds = array();
foreach ( $orders as $index => $order )
{
if ( isset( $foundIds[$order['lid']] ) )
{
$orders[$index]['is_dupe'] = true;
$orders[$foundIds[$order['lid']]]['is_dupe'] = true;
} else {
$orders[$index]['is_dupe'] = false;
}
$foundIds[$order['lid']] = $index;
}
Try this code :
$array_count = array();
foreach ($array as $arr) :
if (in_array($arr, $array_count)) {
foreach ($array_count as $key => $count) :
if ($key == $arr) {
$array_count[$key]++;
break;
}
endforeach;
} else {
$array_count[$arr] = 1;
}
endforeach;
Check with in_array() function.

How to get particular array value in php?

I have the following $qtips_messages array,
Array
(
[0] => Array
(
[id] => 1
[tips_title] => email_tips
[tips_message] => ex:xxxxx#xyz.com
[tips_key] => key_email
)
[1] => Array
(
[id] => 2
[tips_title] => website_tips
[tips_message] => ex:http://www.yahoo.co.in
[tips_key] => key_website
)
[2] => Array
(
[id] => 3
[tips_title] => zipcode_tips
[tips_message] => ex:60612
[tips_key] => key_zipcode
)
[3] => Array
(
[id] => 4
[tips_title] => phone_tips
[tips_message] => ex:1234567890
[tips_key] => key_phone
)
)
For example, I want to get the tips message for the tip_title 'email_tips'
I have tried with following code,
foreach($qtips_messages as $qtipsArray){
foreach($qtipsArray as $qkey=>$qvalue){
if($qtipsArray['tips_title'] == 'email_tips'){
$emailtipsMessage = $qtipsArray['tips_message'];
}
}
}
When i ran the above code i did not get any value.
What is wrong with this code?
You only need one loop:
$message = null;
foreach ($array as $tips) {
if ($tips['tips_title'] == 'email_tips') {
$message = $tips['tips_message'];
break;
}
}
I'd probably go for something like this though:
$message = current(array_filter($array, function ($tip) { return $tip['tips_title'] == 'email_tips'; }));
echo $message['tips_message'];
$array = array();
foreach($result AS $k =>$val)
$array[$val['tips_key']] = $val['tips_message'];
return $array;
Now the array $array have all the values for q-tips based on their keys...
Hope this will helps you...
try this way.
$array = array();
foreach($qtips_messages AS $k =>$val):
if($val['tips_title']=='email_tips')
{
$array[$val['tips_key']] = $val['tips_message'];
print_r($array);
break;
}
endforeach;

Categories