PHP How to calculate duplicate values in array - php

I would like to calculate duplicate values in my array by "groupid":
Example:
Array
(
[0] => Array
(
[id] => 1230
[groupid] => 177
[activity_group_last] => 1229
[name] => First name
)
[1] => Array
(
[id] => 1231
[groupid] => 177
[activity_group_last] => 1229
[name] => Second name
)
[2] => Array
(
[id] => 1232
[groupid] => 178
[activity_group_last] => 1229
[name] => Other name
)
)
Output array (2 groupid = 177 and 1 groupid = 178):
Array
(
[0] => Array
(
[id] => 1231
[groupid] => 177
[activity_group_last] => 1229
[name] => Second name
[count] => 2
)
[1] => Array
(
[id] => 1232
[groupid] => 178
[activity_group_last] => 1229
[name] => Other name
[count] => 1
)
)
Thanks!

If $value contains your array, then:
$count = array_count_values(array_map(function($item) {
return $item['groupid'];
}, $value));
var_dump($count);
$_tmp = $count;
$unique = array_filter($value, function(&$item) use (&$_tmp, $count) {
if (!--$_tmp[$item['groupid']]) {
$item['count'] = $count[$item['groupid']];
return true;
}
return false;
});
var_dump($unique);
results in:
array(2) {
[1]=>
array(5) {
["id"]=>
int(1231)
["groupid"]=>
int(177)
["activity_group_last"]=>
int(1229)
["name"]=>
string(11) "Second name"
["count"]=>
int(2)
}
[2]=>
array(5) {
["id"]=>
int(1232)
["groupid"]=>
int(178)
["activity_group_last"]=>
int(1229)
["name"]=>
string(10) "Other name"
["count"]=>
int(1)
}
}

You can also do this using an iterative function. If your input array is stored in $input and you want the results in $output:
function remove_duplicates($input_array) {
$output_array = array(); // Create an empty array for output
foreach($input_array as $input) { // Loop the input array
if(array_key_exists($input['groupid'], $output_array)) {
// We've already seen this groupid at least once
// Increment count
$input['count'] = $output_array[$input['groupid']]['count'] + 1;
} else {
// First time we've seen this groupid
// Set count to 1
$input['count'] = 1;
}
// Store data in $output_array, indexed by group_id
$output_array[$input['groupid']] = $input;
}
}
// This is your input array
$input = array(array('id'=>1230,'groupid'=>177,'activity_group_last'=>1229,'name'=>'First name'),
array('id'=>1231,'groupid'=>177,'activity_group_last'=>1229,'name'=>'Second name'),
array('id'=>1232,'groupid'=>178,'activity_group_last'=>1229,'name'=>'Other name'));
// This will set the output array correctly
$output = remove_duplicates($input);

Related

How to separate array members I have, being part (Based on number of characters per member / Less than equal to 6)?

My code contains an array that has 7 elements and each element has a total number of different characters. I want, when the number of characters meets the criteria (<= 6) then create a new array.
The output is expected in the form of a two dimension array,
// My Variables, $value & $count
$value=array('as','fix','fine','is','port','none','hi','of');
for ($i=0; $i <count($value) ; $i++) {
$count[]=strlen($value[$i]);
}
Then have output like a,
// $value,
Array
(
[0] => as
[1] => fix
[2] => fine
[3] => is
[4] => port
[5] => none
[6] => hi
[7] => of
)
// Count the length $value and store in Variable $count,
Array
(
[0] => 2
[1] => 3
[2] => 4
[3] => 2
[4] => 4
[5] => 4
[6] => 2
[7] => 2
)
and then I hope my code can produce output like this:
(Explode element where length <= 6)
// If length value in the variable $count,
Array
(
[0] => 2
[1] => 3
Total Length(5)
[2] => 4
[3] => 2
Total Length(6)
[4] => 4
Total Length(4)
[5] => 4
Total Length(4)
[6] => 2
[7] => 2
Total Length(4)
)
This is my question point:
// $Values RESULT
Array
(
[0] => Array
(
[0] => as
[1] => fix
)
[1] => Array
(
[0] => fine
[1] => is
)
[1] => Array
(
[0] => port
)
[1] => Array
(
[0] => none
)
[1] => Array
(
[0] => hi
[1] => of
)
)
Your examples were a bit hard to follow but here's what I've got:
<?php
$value=array('as','fix','fine','is','port','none','hi','of');
$final = [];
$accumulator = 0;
$final[0] = [];
$x = 0;
for ($i=0; $i <count($value) ; $i++) {
var_dump($accumulator);
if($accumulator + strlen($value[$i]) > 6) {
echo "adding ".$value[$i] ." to new\n\n";
$x++;
$final[$x] = [];
array_push($final[$x], $value[$i]);
$accumulator = strlen($value[$i]);
}else{
echo "adding ".$value[$i] . " to existing\n\n";
array_push($final[$x], $value[$i]);
$accumulator += strlen($value[$i]);
}
}
var_dump($final);
Yields
int(0)
adding as to existing
int(2)
adding fix to existing
int(5)
adding fine to new
int(4)
adding is to existing
int(6)
adding port to new
int(4)
adding none to new
int(4)
adding hi to existing
int(6)
adding of to new
array(5) {
[0]=>
array(2) {
[0]=>
string(2) "as"
[1]=>
string(3) "fix"
}
[1]=>
array(2) {
[0]=>
string(4) "fine"
[1]=>
string(2) "is"
}
[2]=>
array(1) {
[0]=>
string(4) "port"
}
[3]=>
array(2) {
[0]=>
string(4) "none"
[1]=>
string(2) "hi"
}
[4]=>
array(1) {
[0]=>
string(2) "of"
}
}
http://sandbox.onlinephpfunctions.com/code/20a63b83ad5524c5cd77e111bc15e197bf8bfba2

How set the array in php?

I have got this Array
Array ( [0] => 9314802498 [1] => 9314801890 [2] => MOSWAPELE ESTHER [3] => BENNETH )
I Want to retrieve like that Array
Array ( [0] => 9314802498 [1] => MOSWAPELE ESTHER [2] => 9314801890 [3] => BENNETH )
This can help -
$array = array ( 0 => 9314802498, 1 => 9314801890, 2 => 'MOSWAPELE ESTHER', 3 => 'BENNETH' );
$temp= array_chunk($array, count($array)/2);
$final = array();
foreach($temp[0] as $key => $val) {
$final[]= $val;
$final[]= !empty($temp[1][$key]) ? $temp[1][$key] : null;
}
var_dump($final);
Output
array(4) {
[0]=>
float(9314802498)
[1]=>
string(16) "MOSWAPELE ESTHER"
[2]=>
float(9314801890)
[3]=>
string(7) "BENNETH"
}
Assuming the count of numbers and names would be equal in that array. If not -
$temp= array_chunk($array, ceil(count($array)/2));
change the key
$arr = Array ( [0] => 9314802498 [1] => 9314801890 [2] => MOSWAPELE ESTHER [3] => BENNETH );
$arr[1] = 'MOSWAPELE ESTHER';
$arr[2] = '9314801890';
It will give you desired answer
Try replacing the key values like this:
$arr1 = array('9314802498', '9314801890', 'MOSWAPELE ESTHER', 'BENNETH');
$temp = $arr1[1];
$arr1[1] = $arr1[2];
$arr1[2] = $temp;
Try this code.
$arr = array(
0 => 9314802498,
1 => 9314801890,
2 => 'MOSWAPELE ESTHER',
3 => 'BENNETH'
);
$temp_val = $arr[1];
$arr[1] = $arr[2];
$arr[2] = $temp_val;
print_r($arr);
Output
Array ( [0] => 9314802498 [1] => MOSWAPELE ESTHER [2] => 9314801890 [3] => BENNETH )

how to sort 2d array php from sql inserted

This is my inseted sql to array
$e=0;
while ($row45 = mysqli_fetch_array($res1)) {
$proIdArr0["id"][$e]=$row45['proId'];
$proIdArr0["qty"][$e]=$row45["proQty"];
$e++;
}
print_r($proIdArr0);
And it prints
Array (
[id] => Array (
[0] => 15
[1] => 13
[2] => 16 )
[qty] => Array (
[0] => 54
[1] => 84
[2] => 54 )
)
and i want to sorted by the id so it will be for example this output
id | qty
-------
13 | 84
15 | 54
16 | 54
You can combine your array and then ksort it.
<?php
$array = [
"id" => [15,13,16],
"qty" => [54,84,54]
];
$combined = array_combine($array['id'], $array['qty']);
ksort($combined);
var_dump($combined);
Returns:
array(3) {
[13]=>
int(84)
[15]=>
int(54)
[16]=>
int(54)
}
Make id as the key and qty as value to sort on id , then some reverse enginering to get desired result.
<?php
$com = array_combine($proIdArr0["id"], $proIdArr0["qty"]);
ksort($com);
foreach($com as $k=>$v)
{
$proIdArr0["id"]=$k;
$proIdArr0["qty"]=$v;
}
But using order by in query is more preferable solution.

how to get value from associative array

This is my array :
Array
(
[0] => Array
(
[0] => S No.
[1] => Contact Message
[2] => Name
[3] => Contact Number
[4] => Email ID
)
[1] => Array
(
[0] => 1
[1] => I am interested in your property. Please get in touch with me.
[2] => lopa <br/>(Individual)
[3] => 1234567890
[4] => loperea.ray#Gmail.com
)
[2] => Array
(
[0] => 2
[1] => This user is looking for 3 BHK Multistorey Apartment for Sale in Sohna, Gurgaon and has viewed your contact details.
[2] => shiva <br/>(Individual)
[3] => 2135467890
[4] => sauron82#yahoo.co.in
)
)
How can I retrieve all data element wise?
You can get information about arrays in PHP on the official PHP doc page
You can access arrays using square braces surrounding the key you like to select [key].
So $array[1] will give yoo:
Array
(
[0] => 1
[1] => I am interested in your property. Please get in touch with me.
[2] => lopa <br/>(Individual)
[3] => 1234567890
[4] => loperea.ray#Gmail.com
)
And $array[1][2] will give you:
lopa <br/>(Individual)
Or you can walkt through the elements of an array using loops like the foreach or the for loop.
// perfect for assoc arrays
foreach($array as $key => $element) {
var_dump($key, $element);
}
// alternative for arrays with seamless numeric keys
$elementsCount = count($array);
for($i = 0; $i < $elementsCount; ++$i) {
var_dump($array[$i]);
}
You have integer indexed elements in multidimensional array. To access single element from array, use array name and it's index $myArray[1]. To get inner element of that previous selected array, use second set of [index] - $myArray[1][5] and so on.
To dynamically get all elements from array, use nested foreach loop:
foreach ($myArray as $key => $values) {
foreach ($values as $innerKey => $value) {
echo $value;
// OR
echo $myArray[$key][$innerKey];
}
}
The solution is to use array_reduce:
$header = array_map(
function() { return []; },
array_flip( array_shift( $array ) )
); // headers
array_reduce( $array , function ($carry, $item) {
$i = 0;
foreach( $carry as $k => $v ) {
$carry[$k][] = $item[$i++];
}
return $carry;
}, $header );
First of all we get the header from the very first element of input array. Then we map-reduce the input.
That gives:
$array = [['A', 'B', 'C'], ['a1', 'b1', 'c1'], ['a2', 'b2', 'c2'], ['a3', 'b3', 'c3']];
/*
array(3) {
'A' =>
array(3) {
[0] =>
string(2) "a1"
[1] =>
string(2) "a2"
[2] =>
string(2) "a3"
}
'B' =>
array(3) {
[0] =>
string(2) "b1"
[1] =>
string(2) "b2"
[2] =>
string(2) "b3"
}
'C' =>
array(3) {
[0] =>
string(2) "c1"
[1] =>
string(2) "c2"
[2] =>
string(2) "c3"
}
}
*/
I think this is what you are looking for
$array = Array
(
0=> Array
(
0 => 'S No.',
1 => 'Contact Message',
2 => 'Name',
3 => 'Contact Number',
4 => 'Email ID'
),
1 => Array
(
0 => 1,
1 => 'I am interested in your property. Please get in touch with me.',
2 => 'lopa <br/>(Individual)',
3 => '1234567890',
4 => 'loperea.ray#Gmail.com',
),
2 => Array
(
0 => 2,
1 => 'This user is looking for 3 BHK Multistorey Apartment for Sale in Sohna, Gurgaon and has viewed your contact details.',
2 => 'shiva <br/>(Individual)',
3 => '2135467890',
4 => 'sauron82#yahoo.co.in',
)
);
$result_array = array();
array_shift($array);
reset($array);
foreach($array as $x=>$array2){
foreach($array2 as $i => $arr){
if($i == 1){
$result_array[$x]['Contact Message'] = $arr;
}elseif($i == 2){
$result_array[$x]['Name'] = $arr;
}elseif($i == 3){
$result_array[$x]['Contact Number'] =$arr;
}elseif($i == 4){
$result_array[$x]['Email ID'] = $arr;
}
}
}
print_r($result_array);

Recreate Multidimensional Array in PHP

This is pretty basic, but my question is:
Given an array:
$a = array(
0 => array('Rate'=> array('type_id'=>1, 'name' => 'Rate_1', 'type'=>'day','value'=>10)),
1 => array('Rate'=> array('type_id'=>1, 'name' => 'Rate_2', 'type'=>'night','value'=>8)),
2 => array('Rate'=> array('type_id'=>2, 'name' => 'Rate_3', 'type'=>'day','value'=>7)),
3 => array('Rate'=> array('type_id'=>2, 'name' => 'Rate_4', 'type'=>'nigh','value'=>16)),
4 => array('Rate'=> array('type_id'=>3, 'name' => 'Rate_5', 'type'=>'day','value'=>10))
);
What is the most efficient way to change it so we have something like:
$new_array = array(
[type_id] => array(
[type] => array(
[value]
)
)
)
);
In other words, I would like to strip some data (the name, which I don't need) and reorganise the dimensions of the array. In the end I would have an array which I would be able to access the values by $new_array['type_id']['type']['value'].
Not entirely sure if this is exactly what you want, but with this you can access the values by saying
echo $new[TYPE_ID][DAY_OR_NIGHT];
$new = array();
foreach($a AS $b){
$c = $b['Rate'];
$new[$c['type_id']][$c['type']] = $c['value'];
}
Using print_r on $new would give you:
Array
(
[1] => Array
(
[day] => 10
[night] => 8
)
[2] => Array
(
[day] => 7
[night] => 16
)
[3] => Array
(
[day] => 10
)
)
Since php 5.3.0, array_reduce() allows using an array as the initial value, given your initial array $a, you can use the following code
function my_reducer ($result, $item) {
$result[$item['Rate']['type_id']][$item['Rate']['type']] = $item['Rate']['value'];
return $result;
}
$assoc_arr = array_reduce($a, 'my_reducer', array());
var_dump($assoc_arr);
This returns
array(3) { [1]=> array(2) {
["day"]=>
int(10)
["night"]=>
int(8) } [2]=> array(2) {
["day"]=>
int(7)
["nigh"]=>
int(16) } [3]=> array(1) {
["day"]=>
int(10) } }

Categories