I have a array as following
array(
0 => array('email' => 'abc#abc.com','name'=>'abc'),
1 => array('email' => 'xyz#abc.com','name'=>'xyz'),
2 => array('email' => 'uvw#abc.com','name'=>'uvw'),
3 => array('email' => 'abc#abc.com','name'=>'str'),
)
I want to filter out records on email address and get records having same email address. For example from above example I want
array(
0 => array(
array(
0 => array('email' => 'abc#abc.com','name'=>'abc'),
1 => array('email' => 'abc#abc.com','name'=>'str'),
)
)
My code is
$tmpArray = array();
$duplicateRecords = array();
if (empty($data)) {
return false;
}
foreach ($data as $key => $value) {
if (in_array($value['Email'], $tmpArray)) {
$duplicateRecords[] = $value;
}
$tmpArray[] = $value['Email'];
}
echo '<pre>';print_r($duplicateRecords);die;
But this piece of code only returns the record's once existance, which is of second time. I know when It is traversing first time it isn't having email to compare. Is there any way to get existence of record as many times as it is in array.
// get count of each email
$counters = array_count_values(array_column($data, 'email'));
// collect email with counter > 1
$result = [];
foreach ($data as $item) {
if ($counters[$item['email']] > 1) {
$result[] = $item;
}
}
This one should work for you:
foreach($array as $key => $value) {
foreach ($array as $k => $v) {
if ($key < $k && $value['email'] == $v['email']) {
$result[] = array(
$value,
$v
);
}
}
}
PHPFiddle Link: http://phpfiddle.org/main/code/8trq-k2zc
Please note: this would only find you the conflicting pairs. For example:
$array = array(
array(
'email' => 'abc#abc.com',
'name' => 'abc'
),
array(
'email' => 'abc#abc.com',
'name' => 'def'
),
array(
'email' => 'abc#abc.com',
'name' => 'ghi'
)
);
Would result in:
Array
(
[0] => Array
(
[0] => Array
(
[email] => abc#abc.com
[name] => abc
)
[1] => Array
(
[email] => abc#abc.com
[name] => def
)
)
[1] => Array
(
[0] => Array
(
[email] => abc#abc.com
[name] => abc
)
[1] => Array
(
[email] => abc#abc.com
[name] => ghi
)
)
[2] => Array
(
[0] => Array
(
[email] => abc#abc.com
[name] => def
)
[1] => Array
(
[email] => abc#abc.com
[name] => ghi
)
)
)
So abc conflicts with def, abc conflicts with ghi, and def conflicts with ghi.
This is a 'two pass' solution. The code is commented.
PHP 5.3.18
<?php // https://stackoverflow.com/questions/26548634/find-all-duplicates-values-in-multi-dimensional-array-php
$data = array(
0 => array('email' => 'abc#abc.com','name'=>'abc'),
1 => array('email' => 'xyz#abc.com','name'=>'xyz'),
2 => array('email' => 'uvw#abc.com','name'=>'uvw'),
3 => array('email' => 'abc#abc.com','name'=>'str'),
);
// two passes required
// first pass: count of emails
$emailCounts = array();
foreach($data as $emailEntry) {
if (isset($emailCounts[$emailEntry['email']])) {
$emailCounts[$emailEntry['email']] += 1;
}
else {
$emailCounts[$emailEntry['email']] = 1;
}
}
// second pass: extract duplicate emails (count > 1)
$duplicateEmails = array();
foreach($data as $emailEntry) {
if ($emailCounts[$emailEntry['email']] > 1) {
$duplicateEmails[] = $emailEntry;
}
}
// show output...
var_dump($emailCounts);
var_dump($duplicateEmails);
Actual output:
array
'abc#abc.com' => int 2
'xyz#abc.com' => int 1
'uvw#abc.com' => int 1
array
0 =>
array
'email' => string 'abc#abc.com' (length=11)
'name' => string 'abc' (length=3)
1 =>
array
'email' => string 'abc#abc.com' (length=11)
'name' => string 'str' (length=3)
Here is the code for you
>$mainarray=array(
0 => array('email' => 'abc#abc.com','name'=>'abc'),
1 => array('email' => 'xyz#abc.com','name'=>'xyz'),
2 => array('email' => 'uvw#abc.com','name'=>'uvw'),
3 => array('email' => 'abc#abc.com','name'=>'str'),
);
foreach($mainarray as $single){
$emailarray[]=$single['email'];
}
foreach(array_count_values($emailarray) as $val => $c)
if($c > 1) $dups[] = $val;
foreach($mainarray as $single){
if(in_array($single['email'], $dups)){
$result[]=$single;
}
}
echo '<pre>';print_r($result);
Related
I have 2 multi arrays, profiles and encoded arrays like this
$profiles = array(
array(
'user_id' => 'fcc3d884-fbef-438a-9c86-0ad52c9b1223',
'first_name' => 'Narñia',
'middle_name' => 'Ñ',
'last_name' => 'Cruz',
'ext' => ''
),
array(
'user_id' => '0d31557d-1e9f-4db3-ac0d-72e1709fe89c',
'first_name' => 'Randy',
'middle_name' => 'O',
'last_name' => 'Rocker',
'ext' => ''
),
array(
'user_id' => '0f93f169-cf56-49df-a76b-7596446104c6',
'first_name' => 'Qwerty',
'middle_name' => 'K',
'last_name' => 'Asdfg',
'ext' => ''
),
array(
'user_id' => '23b1f4a2-034c-43b4-96b7-3191d78cead1',
'first_name' => 'Johny',
'middle_name' => 'L',
'last_name' => 'Walker',
'ext' => ''
)
);
$encoded = array(
array(
'encoder_id' => '0d31557d-1e9f-4db3-ac0d-72e1709fe89c',
'fullname' => 'Randy O. Rocker',
'encoded' => 10,
),
array(
'encoder_id' => '23b1f4a2-034c-43b4-96b7-3191d78cead1',
'fullname' => 'John L. Walker',
'encoded' => 20,
)
);
Now i want to get some data from $profiles then combine to $encoded array when user_id and encoder_id is match, i have this code but it seems wrong it only gets "John L. Waler" data. here's my code.
$data = [];
foreach ($profiles as $key => $val) {
$user_id = $val['user_id'];
foreach($encoded as $k => $v){
$ext_name = ($val['ext'] == '') ? '' : $val['ext'];
$fullname = $val['first_name'].' '.substr($val['middle_name'], 0, 1).'. '.$val['last_name'].' '.$ext_name;
$data[$key] = array(
'id' => ($v['encoder_id'] == $user_id) ? $v['encoder_id'] : $user_id,
'fullname' => ($v['encoder_id'] == $user_id) ? $v['fullname'] : $fullname,
'encoded' => ($v['encoder_id'] == $user_id) ? $v['encoded'] : 0
);
}
}
echo '<pre>';
print_r($data);
echo '</pre>';
here's the result
Array
(
[0] => Array
(
[id] => fcc3d884-fbef-438a-9c86-0ad52c9b1223
[fullname] => Narñia �. Cruz
[encoded] => 0
)
[1] => Array
(
[id] => 0d31557d-1e9f-4db3-ac0d-72e1709fe89c
[fullname] => Randy O. Rocker
[encoded] => 0 //this should be 10
)
[2] => Array
(
[id] => 0f93f169-cf56-49df-a76b-7596446104c6
[fullname] => Qwerty K. Asdfg
[encoded] => 0
)
[3] => Array
(
[id] => 23b1f4a2-034c-43b4-96b7-3191d78cead1
[fullname] => John L. Walker
[encoded] => 20
)
)
Also after combining them to a new array. i want to sort the new array by "encoded" attribute descending.
Thank you for understanding
You can make your life easier by re-indexing the $encoded array by the encoder_id values using array_column; then you don't have to search the array each time to look for a user_id value, you can just use isset. Once you've extracted your data, you can use usort to sort by the encoded values:
$encoded_ids = array_column($encoded, null, 'encoder_id');
$data = array();
foreach ($profiles as $profile) {
$user_id = $profile['user_id'];
if (isset($encoded_ids[$user_id])) {
$data[] = array('id' => $user_id,
'fullname' => $encoded_ids[$user_id]['fullname'],
'encoded' => $encoded_ids[$user_id]['encoded']
);
}
else {
$data[] = array('id' => $user_id,
'fullname' => "${profile['first_name']} ${profile['middle_name']} ${profile['last_name']}",
'encoded' => 0
);
}
}
usort($data, function ($a, $b) { return $b['encoded'] - $a['encoded'];});
print_r($data);
Output:
Array
(
[0] => Array
(
[id] => 23b1f4a2-034c-43b4-96b7-3191d78cead1
[fullname] => John L. Walker
[encoded] => 20
)
[1] => Array
(
[id] => 0d31557d-1e9f-4db3-ac0d-72e1709fe89c
[fullname] => Randy O. Rocker
[encoded] => 10
)
[2] => Array
(
[id] => fcc3d884-fbef-438a-9c86-0ad52c9b1223
[fullname] => Narñia Ñ Cruz
[encoded] => 0
)
[3] => Array
(
[id] => 0f93f169-cf56-49df-a76b-7596446104c6
[fullname] => Qwerty K Asdfg
[encoded] => 0
)
)
Demo on 3v4l.org
An alternative to Nick's version, using array_reduce:
$encodedByEncoderId = array_column($encoded, null, 'encoder_id');
$combined = array_reduce($profiles, function (array $combined, array $profile) use ($encodedByEncoderId): array {
$combined[] = [
'id' => $profile['user_id'],
'fullname' => $encodedByEncoderId[$profile['user_id']]['fullname']
?? "{$profile['first_name']} {$profile['middle_name']}. {$profile['last_name']}",
'encoded' => $encodedByEncoderId[$profile['user_id']]['encoded']
?? 0
];
return $combined;
}, []);
Demo: https://3v4l.org/kKBru
Try this!
$data = [];
foreach ($profiles as $key => $val) {
$user_id = $val['user_id'];
$is_matched = 0;
$encoded_data = [];
foreach($encoded as $k => $v){
if ($user_id == $v['encoder_id']) {
$is_matched = 1;
$encoded_data = $v;
}
}
$ext_name = ($val['ext'] == '') ? '' : $val['ext'];
$fullname = $val['first_name'].' '.substr($val['middle_name'], 0, 1).'. '.$val['last_name'].' '.$ext_name;
$data[$key] = array(
'id' => ($is_matched == 1) ? $encoded_data['encoder_id'] : $user_id,
'fullname' => ($is_matched == 1) ? $encoded_data['fullname'] : $fullname,
'encoded' => ($is_matched == 1) ? $encoded_data['encoded'] : 0
);
}
I have following array..I am trying to group this.
Array
(
[0] => Array
(
[Title] => HoMedics MAN-300
[ean] => 31262006288
[upc] => 31262006288
[ProductImageName] =>
[CdnUri] =>
[ASIN] => B000050FEU
[ListPrice] => 129.99
[Status] => 2
[ActualPrice] => 129.99
[ProductID] => 5286728
)
)
I want to group this into
Array
(
[0] => Array
(
[VitalInfo]=>array(
[Title] => HoMedics MAN-300
[ean] => 31262006288
[upc] => 31262006288
[ProductImageName] =>
[CdnUri] =>
[ASIN] => B000050FEU
)
[Price]=>array(
[ListPrice] => 129.99
[Status] => 2
[ActualPrice] => 129.99
[ProductID] => 5286728
)
)
I tried but it doesn't happen as I want ...any help would be great...Thanx in advance..
try this,
CODE :
foreach($old_array as $key_old => $val_old)
{
foreach($val_old as $key => $val)
{
if(in_array($key, $VitalInfo_array))
{
$new_array[$key_old]['VitalInfo'][$key] = $val;
}
else
{
$new_array[$key_old]['Price'][$key] = $val;
}
}
}
OUTPUT :
Array
(
[0] => Array
(
[VitalInfo] => Array
(
[Title] => HoMedics MAN-300
[ean] => 31262006288
[upc] => 31262006288
[ProductImageName] =>
[CdnUri] =>
[ASIN] => B000050FEU
)
[Price] => Array
(
[ListPrice] => 129.99
[Status] => 2
[ActualPrice] => 129.99
[ProductID] => 5286728
)
)
)
DEMO
i hope it will be helpful.
Simply loop through your array and customize a new array accordingly.
Assuming $array is the original array, and $result is the customized array, try this:
foreach ($array as $k => $arr) {
$result[$k]['VitalInfo'] = array(
'Title' => $arr['Title'],
'ean' => $arr['ean'],
'upc' => $arr['upc'],
'ProductImageName' => $arr['ProductImageName'],
'CdnUri' => $arr['CdnUri'],
'ASIN' => $arr['ASIN']
);
$result[$k]['Price'] = array(
'ListPrice' => $arr['ListPrice'],
'Status' => $arr['Status'],
'ActualPrice' => $arr['ActualPrice'],
'ProductID' => $arr['ProductID']
);
}
Input : $info // Your Original Array
Ouput : $finalArr // Your Required Array
$vitalInfo = array ('Title','ean','upc','ProductImageName','CdnUri','ASIN');
$price = array ('ListPrice','Status','ActualPrice','ProductId');
$finalArr = array();
foreach ($info as $arr) {
$result = array();
foreach($arr as $k => $v){
if(in_array($k,$vitalInfo))
$result['VitalInfo'][$k] = $v;
else if(in_array($k,$price))
$result['Price'][$k] = $v;
}
$finalArr[] = $result;
}
If you are grouping this in php, have a look at these answers.
Or just copy this:
$input = [0 => [
'Title' => 'HoMedics MAN-300',
'ean' => 31262006288,
'upc' => 31262006288,
'ProductImageName' => '',
'CdnUri' => '',
'ASIN' => 'B000050FEU',
'ListPrice' => 129.99,
'Status' => 2,
'ActualPrice' => 129.99,
'ProductID' => 5286728
]];
foreach ($input as $in){
$out['VitalInfo'] = [];
$out['Price'] = [];
foreach ($in as $key => $i){
if (in_array($key, ['Title', 'ean', 'upc', 'ProductImageName', 'CdnUri', 'Asin'])){
$out['VitalInfo'][] = [$key => $i];
} else {
$out['Price'][] = [$key => $i];
}
}
$output[]=$out;
}
echo '<pre>';
var_dump($output);
I'm trying to read a session variable, create arrays and concatenate them :
Session variable sample:
Array
(
[0] => Array
(
[idArticle] => 224
[ntypeArticle] => 1
)
[1] => Array
(
[idArticle] => 556
[ntypeArticle] => 2
)
[2] => Array
(
[idArticle] => 312
[ntypeArticle] => 1
)
)
I need to read this arrays one by one and create arrays by "ntypeArticle".
If ntypeArticle=1, create array1
If ntypeArticle=2, create array2
My code :
$type1 = array();
$type2= array();
$typeAll = array();
foreach($_SESSION['cart'] as $item)
{
if ($item['ntypeArticle'] == 1) {
$type1= array ( "Type" => '1', );
} else {
$type2= array ( "Type" => '2', );
}
array_push($typeAll , $type1 , $type2);
}
But this creates empty arrays.
Wanted output :
Array
(
[0] => Array
(
[type] => 1
)
[1] => Array
(
[type] => 2
)
[2] => Array
(
[type] => 1
)
)
All you need is this simple thing:
$out = [];
foreach($_SESSION['cart'] as $k => $item)
{
$out[$k] = ['Type' => $item['ntypeArticle']];
}
Now if you output $out variable you get what you need.
Try This
$newOp1 = array()
$newOp2 = array()
foreach($_SESSION['cart'] as $item){
if($item["ntypeArticle"] == 1){
$newOp1[]['type'] = $item["ntypeArticle"]
}else{
$newOp2[]['type'] = $item["ntypeArticle"]
}
}
print_r($newOp1);
print_r($newOp2);
Basing on information you provided, all you want to do is to extract nTypeArticle as type element. That's all.
//array from your example
$inputArray = array(
array(
'idArticle' => 224,
'nTypeArticle' => 1
),
array(
'idArticle' => 556,
'nTypeArticle' => 2
),
array(
'idArticle' => 312,
'nTypeArticle' => 1
),
);
$outputArray = array_map(function($inputElement) {
return array('type' => $inputElement['nTypeArticle']);
}, $inputArray);
var_dump($outputArray);
//Output (the same as yours):
//array (size=3)
// 0 =>
// array (size=1)
// 'type' => int 1
// 1 =>
// array (size=1)
// 'type' => int 2
// 2 =>
// array (size=1)
// 'type' => int 1
$output = new array();
$input = array(
array(
"idArticle" => 224,
"nTypeArticle" => 1
),
array(
"idArticle" => 556,
"nTypeArticle" => 2
),
array(
"idArticle" => 312,
"nTypeArticle" => 1
)
);
foreach($input as $article) {
array_push($output, new array("type"=>$article["nTypeArticle"]));
}
print_r($output);
This gives you the thing you asked for.
(Code has been not tested)
I am getting this array when form is submitted
array
'item' =>
array
0 => string 'Salt'
1 => string 'Pepper'
'quantity' =>
array (size=2)
0 => string '2 spoon'
1 => string '5'
and now want to rearrange above array, so it should look like
array
'0' =>
array
'item' => string 'Salt'
'quantity' => string '2 spoon'
'1' =>
array
'item' => string 'Pepper'
'quantity' => string '5'
I tried so many combinations but failed, will somebody help me how to rearrange this array. Any help will be more than appreciated.
Try this
$array = array(
'item' =>
array(
0 => 'Salt',
1 => 'Pepper'),
'quantity' =>
array(
0 => '2 spoon',
1 => '5')
);
$new_array = array();
foreach ($array['item'] as $key => $value) {
$new_array[$key]["item"] = $value;
$new_array[$key]["quantity"] = $array['quantity'][$key];
}
echo "<pre>";
var_dump($new_array);
Do it as below -
<?php
$arr=array(
'item' =>
array(
0 => 'Salt' ,
1 => 'Pepper'
),
'quantity' =>
array (
0 =>'spoon',
1 =>'5'
)
);
$result=array();
$com=array_combine($arr['item'],$arr['quantity']);
foreach($com as $k=>$v)
{
$result[]=array("item"=>$k,"quantity"=>$v);
}
print_r($result);
?>
OUTPUT
Array (
[0] => Array ( [item] => Salt [quantity] => spoon )
[1] => Array ( [item] => Pepper [quantity] => 5 )
)
try this, I think this would help you,
$a = array(
'item' =>
array(
0 => 'Salt',
1 => 'Pepper'),
'quantity' =>
array(
0 => '2 spoon',
1 => '5')
);
$i = 0;
foreach($a['item'] as $row){
$b[$i]["item"] = $row;
$b[$i]["quantity"] = $a['quantity'][$i];
$i++;
}
print_r($b);
Output from print_r() will be
Array
(
[0] => Array
(
[item] => Salt
[quantity] => 2 spoon
)
[1] => Array
(
[item] => Pepper
[quantity] => 5
)
)
You can simply use array_walk like as
$result = [];
array_walk($arr['item'], function($v, $k)use(&$result, $arr) {
$result[$k]['item'] = $arr['item'][$k];
$result[$k]['quantity'] = $arr['quantity'][$k];
});
print_r($result);
Demo
Hoping that your array is stored in the $array variable and that item is leading. Meaning that there is always an item in the array and not always a quantity
<?php
foreach($array['item'] as $key => $item) {
$newArray[$key]['item'] = $item;
if (isset($array['quantity'][$key]) {
$newArray[$key]['quantity'] = $array['quantity'][$key];
} else {
$newArray[$key]['quantity'] = 0;
}
?>
I have an array $result as follows
Array
( [0] => Array (
[0] => Mr
[1] => vinay
[2] => hs
[3] => tester
[4] =>vinay.hs#abc.com
[5] => 909099
[6] => Yes )
[1] => Array (
[0] => Mr
[1] => Suresh
[2] => Kumar
[3] => tester
[4] => vinay.hs#abc.com
[5] => 809090
[6] => No )
).
I want to store this array as
Array
([0]=>Array (
[title] => Mr
[firstname] => vinay
[lastname] => hs
[job_title] => tester
[email] =>vinay.hs#abc.com
[phone] => 909099
[is_employed] => Yes )
[1] => Array (
[title] => Mr
[firstname] => Suresh
[lastname] => Kumar
[job_title] => tester
[email] => vinay.hs#abc.com
[phone] => 809090
[is_employed] => No ) ).
Explain me how to do this
$fp = fopen('foo.csv', 'r');
$fields = fgetcsv($fp); // assumes fields are the first row in the file
// or $fields = array('title', 'firstname', 'lastname', 'job_title', 'email', 'phone', 'is_employed');
$records = array();
while ($record = fgetcsv($fp))
{
$records[] = array_combine($fields, $record);
}
Obviously it needs error handling added to it.
$newarray=array();
foreach($result as $res) {
$a = array();
$i = 0;
foreach(array('title','firstname','lastname','job_title','email','phone','is_employed') as $key) {
$a[$key] = $res[$i++];
}
$newarray[] = $a;
}
$arr = array("title" => "Mr", "title" => "vinay", "key" => "value")
access it with:
$arr["title"]
array(
array(
'title' => 'Mr',
'firstname' => 'vinay',
'lastname' => 'hs',
'job_title' => 'tester',
'email' => 'vinay.hs#abc.com',
'phone' => '909099',
'is_employed' => TRUE
),
array(
'title' => 'Mr',
'firstname' => 'Suresh',
'lastname' => 'Kumar',
'job_title' => 'tester',
'email' => 'vinay.hs#abc.com',
'phone' => '809090',
'is_employed' => FALSE
)
);
UPDATED:
My answer previously is dumb. If you are loading from CSV file, assuming the first element of array is the keys.
You might want to do something like this.
Sorry for my bad naming.
$keysArray = array_shift($arrayFromCSV);
$wantedArrayStructure = array();
foreach ($arrayFromCSV as $person) {
$item = array();
foreach ($person as $key => $value) {
$item[$keysArray[$key]] = $value;
}
$wantedArrayStructure[] = $item;
}
var_dump($wantedArrayStructure);
If, is is result from msql query. You should using function to get the expected result:
mysql_fetch_assoc