compare array data and get an merged output in php - php

I have an array like this. I want remove elements with duplicate id and get sum of the count
array(3) {
[0]=>
array(3) {
["Id"]=>
string(1) "1"
["Name"]=>
string(1) "a"
["Count"]=>
string(1) "2"
}
[1]=>
array(3) {
["Id"]=>
string(1) "2"
["Name"]=>
string(1) "b"
["Count"]=>
string(1) "1"
}[2]=>
array(3) {
["Id"]=>
string(1) "1"
["Name"]=>
string(1) "a"
["Count"]=>
string(1) "1"
}
}
and I need to remove elements with duplicate id and get sum of the count as shown below
array(2) {
[0]=>
array(3) {
["Id"]=>
string(1) "1"
["Name"]=>
string(1) "a"
["Count"]=>
string(1) "3"
}[1]=>
array(3) {
["Id"]=>
string(1) "2"
["Name"]=>
string(1) "b"
["Count"]=>
string(1) "1"
}
}
I have gone through many examples.. but couldn't find an answer..

Unfortunately there is no way around looping. Assuming that Name is the same for the same Id or that you don't care about the value of Name:
foreach($array as $value) {
if(!isset($result[$value['Id']])) {
$result[$value['Id']] = $value;
} else {
$result[$value['Id']]['Count'] += $value['Count'];
}
}
// re-index if needed
$result = array_values($result);
Loop the array and build result array using Id as key
If the key Id doesn't exist create it
If it does exist add Count to the current Count

just create a new array, loop through current, create if doesnt exist, and insert values (sum) into new one
what are you doing with duplicates names?
example below. hope it will help.
<?php
$tArr = array(
array(
"Id" => "1",
"Name" => "a",
"Count" => "2",
),
array(
"Id" => "2",
"Name" => "b",
"Count" => "1",
),
array(
"Id" => "1",
"Name" => "a",
"Count" => "1",
)
);
$rez = array();
foreach ($tArr as $key => $element) {
if (empty($rez[$element["Id"]])) {
$rez[$element["Id"]] = $element;
} else {
$rez[$element["Id"]]["Count"] += $element["Count"];
}
}
var_dump($rez);
/** array (size=2)
1 =>
array (size=3)
'Id' => string '1' (length=1)
'Name' => string 'a' (length=1)
'Count' => int 3
2 =>
array (size=3)
'Id' => string '2' (length=1)
'Name' => string 'b' (length=1)
'Count' => string '1' (length=1)**/

Try this
$result = array_diff_assoc($arr, array_unique($arr));
print_r($result);

Related

Echo two multidimensional array with different table

So I have this kind of project to have post divided into several provinces. I have two multidimensional array with table1 and table2, I have been trying to echo it with foreach function and etc but still error. This is my array :
array(2) {
[0]=>
array(1) {
[1]=>
array(2) {
["table1"]=>
array(12) {
[0]=>
string(1) "1"
["id_province"]=>
string(1) "1"
[1]=>
string(13) "Province A"
["nm_province"]=>
string(13) "Province A"
}
["table2"]=>
array(2) {
[0]=>
array(58) {
[0]=>
string(2) "43"
["id_news"]=>
string(2) "43"
[1]=>
string(1) "1"
["id_province"]=>
string(1) "1"
[2]=>
string(23) "News A"
["nm_news"]=>
string(23) "News A"
}
[1]=>
array(58) {
[0]=>
string(3) "123"
["id_news"]=>
string(3) "123"
[1]=>
string(1) "1"
["id_province"]=>
string(1) "1"
[2]=>
string(21) "News B"
["nm_news"]=>
string(21) "News B"
}
}
}
}
[1]=>
array(1) {
[2]=>
array(2) {
["table1"]=>
array(12) {
[0]=>
string(1) "2"
["id_province"]=>
string(1) "2"
[1]=>
string(23) "Province B"
["nm_province"]=>
string(23) "Province B"
}
["table2"]=>
array(2) {
[0]=>
array(58) {
[0]=>
string(2) "44"
["id_news"]=>
string(2) "44"
[2]=>
string(1) "2"
["id_province"]=>
string(1) "2"
[5]=>
string(24) "News A Province B"
["nm_news"]=>
string(24) "News A Province B"
}
[1]=>
array(58) {
[0]=>
string(3) "127"
["id_news"]=>
string(3) "127"
[2]=>
string(1) "2"
["id_province"]=>
string(1) "2"
[5]=>
string(13) "News B Province B"
["nm_news"]=>
string(13) "News B Province B"
}
}
}
}
}
I don't have any idea how to retrieve more than 2 table in my array with. So I repeat again I want to echo this 2 table the 1st province had 2 news and 2nd province also had 2 news, What I want to do is echo this 2 news sorting with province.
Ps. This is my code to show arrays output
<?php
$a=mysql_query("select * from province");
while($m1=mysql_fetch_array($a)){
$result[]=$m1;
}
$output=[];
$i=0;
foreach($result as $r){
$b=$r['id_province'];
$c=mysql_query("select * from news where id_province=".$b);
$output[$i][$b]['table1']=$r;
$dummy=[];
while($response = mysql_fetch_array($c)){
$dummy[] = $response;
}
$output[$i][$b]['table2']=$dummy;
$i++;
}
Thanks For helping guys.
update below code it will work for you..
foreach($result as $r){
$b=$r['id_province'];
$c=mysql_query("select * from news where id_province=".$b);
$output[$i]['table1']=$r;
$dummy=[];
while($response = mysql_fetch_array($c)){
$dummy[] = $response;
}
$output[$i]['table2']=$dummy;
$i++;
}
Here i have removed extra [$b] from $output array.
Now copy below code to print array.
foreach($output as $out){
$table1= $out['table1'];
$table2= $out['table2'];
echo $table1['nm_provinsi'].'<br>';
echo 'Data from table 2';
foreach($table2 as $tab2){
echo "\t".$tab2['nm_berita'].'<br>';
}
}
I'd say you'd need to clean up your array first to make sure you are trying to reference the right object, you seem to have everything duplicated with an index and a key in the array.
[0]=>"123",
["id_news"]=>"123",
[1]=>"1",
["id_province"]=>"1",
[2]=>"News B",
["nm_news"]=>"News B",
Edit
I've broken down your array so you can see what I mean clearly
array(
'table1' => array(
'0' => 1,
'id_province' => 1,
'1' => 'Province A',
'nm_province' => 'Province A'
),
'table2' => array(
array(
'0' => '43',
'id_news' => '43',
'1' => '1',
'id_province' => '1',
'2' => 'News A',
'nm_news' => 'News A'
),
array(
'0' => '123',
'id_news' => '123',
'1' => 1,
'id_province' => '1',
'2' => 'New B',
'nm_news' => 'News B')
)
),
array(
'table1' => array(
'0' => "2",
'id_province' => "2",
'1' => "Province B",
'nm_province' => 'Province B'
),
'table2' => array(
array(
'0'=>'44',
'id_news' => '44',
'2' => '2',
'id_province' => '2',
'5' => 'News A Province B',
'nm_news' => 'News A Province B'
),
array(
'0'=>'127',
'id_news' => '127',
'2'=>'2',
'id_province' => '2',
'5' => 'News B Province B',
'nm_news' => 'News B Province B'
)
)
)
Try
$c=mysql_query("select * from news where id_province='$b'");

Combine arrays with common keys for MYSQL update

I have four $_POST arrays generated from multiple rows of a table
$event_id_array = $_POST['event_id'];
$booth_array = $_POST['booth'];
$parking_array = $_POST['parking'];
$load_in_array = $_POST['load_in'];
I would like to rearrange the arrays to be keyed by $event_id_array as the key of each of the other arrays = an 'event_id'
Arrays are:
$event_id_array =
array(52) {
["'3'"]=>
string(1) "3"
["'5'"]=>
string(1) "5"
["'7'"]=>
string(1) "7"
["'8'"]=>
string(1) "8"
}
$booth_array =
array(52) {
["'3'"]=>
string(1) "1"
["'5'"]=>
string(1) "2"
["'7'"]=>
string(1) "4"
["'8'"]=>
string(0) ""
}
$parking_array =
array(52) {
["'3'"]=>
string(1) "1"
["'5'"]=>
string(1) "2"
["'7'"]=>
string(0) ""
["'8'"]=>
string(0) ""
}
$load_in_array =
array(52) {
["'3'"]=>
string(4) "1:00"
["'5'"]=>
string(4) "2:00"
["'7'"]=>
string(4) "1:15"
["'8'"]=>
string(0) ""
}
I would like the new array to be efficiently update a MySQL database and was thinking a structure of the following would be best:
array(
event_id[3] => array(
'booth' => "1",
'parking' => "1",
'load_in' => "1:00"),
event_id[5] => array(
'booth' => "2",
'parking' => "2",
'load_in' => "2:00"),
event_id[7] => array(
'booth' => "4",
'parking' => "",
'load_in' => "1:15"),
event_id[8] => array(
'booth' => "",
'parking' => "",
'load_in' => ""),
)
or any other way to easily update multiple records easily

Restructure array data by chunking, transposing, and merging

I have array mentioned below, I will have value always multiple of 3.
$xyz = [
["name" => "abc"],
["name" => "snds"],
["name" => ""),
["number"=> "452"],
["number" => "845120"],
["number" => "84514513200"],
["email" => "ddddf"],
["email" => "dkskns"],
["email" => "kjnksdnkds"]
];
but this is not the proper format for me to perform further operations, so I want this array like mentioned below.
$abc = [
[
"name" => "abc",
"number" => '452',
"email" => "ddddf"
],
[
"name" => "snds",
"number" => "845120",
"email" => "dkskns"
],
[
"name" => "",
"number" => "84514513200",
"email" => "kjnksdnkds"
]
];
note: the array length is dynamic but it will always be multiple of 3
One possibility could be to use the modulo % operator.
In the foreach the value is an array and you could use array_keys to get the key and reset to get the value of the first array element.
$result = [];
$count = 0;
foreach ($xyz as $value) {
if ($count%3 === 0) {
$count = 0;
}
$result[$count][array_keys($value)[0]] = reset($value);
$count++;
}
Demo
That will give you:
array(3) {
[0]=>
array(3) {
["name"]=>
string(3) "abc"
["number"]=>
string(3) "452"
["email"]=>
string(5) "ddddf"
}
[1]=>
array(3) {
["name"]=>
string(4) "snds"
["number"]=>
string(6) "845120"
["email"]=>
string(6) "dkskns"
}
[2]=>
array(3) {
["name"]=>
string(0) ""
["number"]=>
string(11) "84514513200"
["email"]=>
string(10) "kjnksdnkds"
}
}
This will do:
$result = array_map('array_merge', ...array_chunk($xyz, count($xyz) / 3));

Strange array layout while using array_push with multidimensional arrays

Sorry if there's too much code in this question. Arrays takes up a lot of space and I'm trying to explain this as thorough as I can. I'm trying to save all of the addresses user entered into one multidimensional array, so I could easily loop trough them after. Final result of what I'm trying to achieve in theory looks like this:
array(3) {[0]=>
array(4) {
["street_address"]=>
string(1) "a"
["city_name"]=>
string(1) "a"
["zip"]=>
string(1) "a"
["country_select"]=>
string(2) "LT"
}
[1]=>
array(4) {
["street_address"]=>
string(1) "b"
["city_name"]=>
string(1) "b"
["zip"]=>
string(1) "b"
["country_select"]=>
string(2) "LT"
}
[2]=>
array(4) {
["street_address"]=>
string(1) "c"
["city_name"]=>
string(1) "c"
["zip"]=>
string(1) "c"
["country_select"]=>
string(2) "LT"
}}
I could easily replicate this with simple code
$adresai = array();
$adresas =array(
'street_address' => 'a',
'city_name' => 'a',
'zip' => 'a',
'country_select' => 'a');
array_push($adresai, $adresas);
array_push($adresai, $adresas);
array_push($adresai, $adresas);
but when I'm trying to apply this logic in wordpress I get really strange layout, basically a mess.
array(1) {
[0]=>
array(2) {
[0]=>
array(2) {
[0]=>
array(4) {
["street_address"]=>
string(1) "a"
["city_name"]=>
string(1) "a"
["zip"]=>
string(1) "a"
["country_select"]=>
string(2) "LT"
}
[1]=>
array(4) {
["street_address"]=>
string(1) "b"
["city_name"]=>
string(1) "b"
["zip"]=>
string(1) "b"
["country_select"]=>
string(2) "LT"
}
}
[1]=>
array(4) {
["street_address"]=>
string(1) "c"
["city_name"]=>
string(1) "c"
["zip"]=>
string(1) "c"
["country_select"]=>
string(2) "LT"
}}}
My snippet for saving user entered address and merging with previous ones:
$adresai =get_user_meta(get_current_user_id(), 'stakliu_adresai');
$adresas =array(
'street_address' => $_POST['snr_gatve'],
'city_name' => $_POST['snr_miestas'],
'zip' => $_POST['snr_pastokodas'],
'country_select' => $_POST['snr_salis']);
if ($adresai == array()){
$adresai = $adresas;
}
else{
array_push($adresai, $adresas);
}
update_user_meta(get_current_user_id(),'stakliu_adresai', $adresai );
What am I doing wrong?
I would say part of your issue lies in:
if ($adresai == array()) {
$adresai = $adresas;
}else ...
You are planning on storing multiple addresses. An array of arrays. If the value does not exist, you are simply setting it to an array, as opposed to adding it to an array. Since you are expecting an empty array if nothing is set, you can simply push regardless, like so:
$adresai =get_user_meta(get_current_user_id(), 'stakliu_adresai');
$adresas = array(
'street_address' => $_POST['snr_gatve'],
'city_name' => $_POST['snr_miestas'],
'zip' => $_POST['snr_pastokodas'],
'country_select' => $_POST['snr_salis']
);
//if the array is empty, this address will become the first value
//if the array is not empty, this address will be added to the array
array_push($adresai, $adresas);
//save
update_user_meta(get_current_user_id(),'stakliu_adresai', $adresai );
So as naththedeveloper advised, I added parameter $single = true, which returns meta value without additional array "wrapping". But when meta is not set yet, function returns an empty string. To avoid errors I still had to use conditional statement. I finally got it working with this:
$adresai = get_user_meta(get_current_user_id(), 'stakliu_adresai', true);
$adresas = array(
'street_address' => $_POST['snr_gatve'],
'city_name' => $_POST['snr_miestas'],
'zip' => $_POST['snr_pastokodas'],
'country_select' => $_POST['snr_salis']);
// checking if value was not set earlier
if ($adresai == ''){
$adresai = array();
}
array_push($adresai, $adresas);
update_user_meta(get_current_user_id(),'stakliu_adresai', $adresai );

Get the array set which has a distinct value for key PHP

array(
[0]=> array(3)
{
[0]=> array(3)
{
["name"]=> string(1) "a" ,
["code"]=> string(3) "416" ,
["id"]=> string(2) "a1" ,
},
[1]=> array(3)
{
["name"]=> string(1) "a",
["code"]=> string(3) "522" ,
["id"]=> string(2) "a2",
},
[2]=> array(3)
{
["name"]=> string(1) "b" ,
["code"]=> string(3) "580" ,
["id"]=> string(2) "b1" ,
}
},
[1]=> array(3)
{
[0]=> array(3)
{
["name"]=> string(1) "a" ,
["code"]=> string(3) "416" ,
["id"]=> string(2) "a1" ,
},
[1]=> array(3)
{
["name"]=> string(1) "a" ,
["code"]=> string(3) "522" ,
["id"]=> string(2) "a2" ,
},
[2]=> array(3)
{
["name"]=> string(1) "b" ,
["code"]=> string(3) "899" ,
["id"]=> string(2) "b2",
}
}
);
I have array like this. All I need is for each array (e.g [0]=>array())
I will search for the arrays inside and get the array['code'] only for array set that has distinct name value.
Example for array[0]: I will get the array[0][2]['code'] because the array set of this particular array[0][2]['code'] has a unique 'name'
Assume in the below code $array is $arr[0] from your example:
$array = array(
array(
"name" => "a",
"code" => "416",
"id" => "a1"
),
array(
"name" => "a",
"code" => "522",
"id" => "a2"
),
array(
"name" => "b",
"code" => "580",
"id" => "b1"
)
);
$counts = array_count_values(
array_map(function (array $entry) { return $entry['name']; }, $array)
// or array_column($array, 'name') in PHP 5.5+
);
$uniqueNames = array_keys(
array_filter($counts, function ($count) { return $count == 1; })
);
$result = array_filter($array, function (array $entry) use ($uniqueNames) {
return in_array($entry['name'], $uniqueNames);
});
Not necessarily the super most efficient method, but straight forward and functional. It filters the array down to the entries where name exists only once. This may or may not fit your definition of "unique", it's rather unclear what variations in the input data you may have.

Categories