merge two array with the same key and value - php

I have arrays of $array_one:
print_r($array_one);
Array
(
[0] => stdClass Object
(
[myid] => 653509
[date] => 2015-03-15 00:07:03
)
[1] => stdClass Object
(
[myid] => 653511
[date] => Never
)
[2] => stdClass Object
(
[myid] => 653530
[date] => 2015-03-15 02:06:26
)
And then the arrays of $array_two;
print_r($array_two);
Array
(
[0] => stdClass Object
(
[myid] => 653530
[pin] => 12fdg34345
)
[1] => stdClass Object
(
[myid] => 653509
[pin] => 1we2534dgf5
)
[2] => stdClass Object
(
[myid] => 653511
[pin] => 12wer3u45
)
and then I want to merge it based on the keys with the same value, in which the expected result would be:
Array
(
[0] => stdClass Object
(
[myid] => 653530
[pin] => 12fdg34345
[date] => 2015-03-15 02:06:26
)
[1] => stdClass Object
(
[myid] => 653509
[pin] => 1we2534dgf5
[date] => 2015-03-15 00:07:03
)
[2] => stdClass Object
(
[myid] => 653511
[pin] => 12wer3u45
[date] => Never
)
from the result above, the array key of date from the first_array is push to
the second_array based on the similar value of the key of my_id.
Is there a way to do this?
Please help and many thanks for the help.
Cheers!

As per my comment, this solution depends on the structure changing very slightly, to be arrays of associative arrays, not arrays of objects. As you said the data is coming from (a) database(s), if you're using something like PDO, this should just mean a small change to set the correct fetch mode.
The result can be achieved by combining the php built-in functions array_column and array_replace_recursive. If you want the resulting array to still be 0-indexed, we can use array_values too.
$array_one = [
[
'myid' => 653509,
'date' => '2015-03-15 00:07:03'
],
[
'myid' => 653511,
'date' => 'Never'
],
[
'myid' => 653530,
'date' => '2015-03-15 02:06:26'
]
];
$array_two = [
[
'myid' => 653530,
'pin' => '12fdg34345'
],
[
'myid' => 653509,
'pin' => '1we2534dgf5'
],
[
'myid' => 653511,
'pin' => '12wer3u45'
]
];
$merged = array_replace_recursive(
array_column($array_one, null, 'myid'),
array_column($array_two, null, 'myid')
);

<?php
$temp_arr_one = array();
foreach($array_one as $key1=>$val1){
$temp_arr_one[$val1['myid']] = $val1->date;
}
$final_arr = array();
foreach($array_two as $key2=>$val2){
$final_arr[$key2]['myid'] = $val2->myid;
$final_arr[$key2]['pin'] = $val2->pin;
$final_arr[$key2]['date'] = $temp_arr_one[$val2->myid];
}
print_r($final_arr);
?>

Related

Merge subarrays of multidimensional array based on sub value

I have a multidimensional array like this, I need to merge subarrays with the same messageID value.
$myarray = Array (
[0] => Array
(
[messageId] => 5ACE9D8841
[sender] => john#doe.com
)
[1] => Array
(
[messageId] => 7EE67D8170
[sender] => dan#doe.com
)
[2] => Array
(
[messageId] => 8095FD8836
[sender] => cat#doe.com
)
[3] => Array
(
[messageId] => 7EE67D8170
[dest] => mitch#doe.com
[status] => sent
[date] => 2021-02-01 11:06:55
)
);
Expected result , [1] and [3] are merged into [1] because they share the same [messageId] :
Array
(
[0] => Array
(
[messageId] => 5ACE9D8841
[sender] => john#doe.com
)
[1] => Array
(
[messageId] => 7EE67D8170
[dest] => mitch#doe.com
[status] => sent
[date] => 2021-02-01 11:06:55
[sender] => dan#doe.com
)
[2] => Array
(
[messageId] => 8095FD8836
[sender] => cat#doe.com
)
)
I don't mind about the key index or the order.
EDIT : I've tried array_merge, array_merge_recursive and many others. Best result was obtained with
foreach ($myarray as $sub_arr) {
$result_arr = array_merge($result_arr, $sub_arr);
$result_arr = array_unique($result_arr);
}
It works but returns only the last iteration :
Array
(
[messageId] => 7EE67D8170
[dest] => mitch#doe.com
[status] => sent
[date] => 2021-02-01 11:06:55
[sender] => dan#doe.com
)
Regards
Try using array_reduce function with callback function:
$result = array_values(array_reduce($myarray, function($rows, $item){
if (array_key_exists('messageId', $item) && is_scalar($item['messageId'])) {
$rows = array_replace_recursive($rows ?? [], [$item['messageId'] => $item]);
}
return $rows;
}));
print_r($result);
fiddle

Access JSON Array Data Within Object With PHP

stdClass Object (
[id] => 8586332
[email] => hello#myemail.com
[optInType] => Unknown
[emailType] => Html
[dataFields] => Array
(
[0] => stdClass Object ( [key] => FIRSTNAME [value] => Bill )
[1] => stdClass Object ( [key] => FULLNAME [value] => Bill Jones )
[2] => stdClass Object ( [key] => GENDER [value] => )
[3] => stdClass Object ( [key] => LASTNAME [value] => Jones )
[4] => stdClass Object ( [key] => LASTSUBSCRIBED [value] => 2019-12-20T21:13:20.359947Z )
[5] => stdClass Object ( [key] => POSTCODE [value] => )
[6] => stdClass Object ( [key] => THIS_KEY [value] => This Value )
)
[status] => Subscribed )
I have this JSON object and array in PHP that I have decoded.
I am trying to access 'This Value' but I am stuck.
I also need to find a way to do it where I don't know if it will always be number 6.
I have made these attempts:
$object->{"dataFields[1]"};
and
$object['dataFields'][6]['THIS_KEY'];
I can access the email like this:
echo $objec[1]->email;
You will need to search through the subarray for the qualifying object using the key property's value.
There will be functional techniques to do this, but I'll show a simple loop and break technique.
Code: (Demo)
$object = (object) [
'id'=> 8586332,
'email' => 'hello#myemail.com',
'optInType' => 'Unknown',
'emailType' => 'Html',
'dataFields' => [
(object)['key' => 'FIRSTNAME', 'value' => 'Bill'],
(object)['key' => 'FULLNAME', 'value' => 'Tom Jones'],
(object)['key' => 'GENDER', 'value' => ''],
(object)['key' => 'LASTNAME', 'value' => 'Jones'],
(object)['key' => 'LASTSUBSCRIBED', 'value' => '2019-12-20T21:13:20.359947Z'],
(object)['key' => 'POSTCODE', 'value' => ''],
(object)['key' => 'THIS_KEY', 'value' => 'This Value'],
],
'status' => 'Subscribed'
];
foreach ($object->dataFields as $dataRow) {
if ($dataRow->key === 'THIS_KEY') {
echo $dataRow->value;
break;
}
}
Output:
This Value
A functional search can look like this: (Demo)
$index = array_search('THIS_KEY', array_column($object->dataFields, 'key'));
if ($index !== false) {
echo $object->dataFields[$index]->value; // same output as above
}
If you want simpler access to multiple values in the subarray, then assign temporary keys: (Demo)
$assocDataFields = array_column($object->dataFields, null, 'key');
echo $assocDataFields['THIS_KEY']->value;
echo "\n";
echo $assocDataFields['FULLNAME']->value;
Output:
This Value
Tom Jones

PHP Array Unique Sort Regular not working as expected

I'm using print_r(array_unique($array, SORT_REGULAR)); on the array below but it does not work.
I'm trying to filter out the redundant data.
Notice that [Order] and its key value pairs are all the same. But [Transaction] and its key value pairs are unique.
I need to get the [Order] element data and combine it with the 3 different [Transaction] elements.
My array
Array
(
[0] => Array
(
[Order] => Array
(
[PO] => TR11214
[OrderID] => 242856952012
)
[Transaction] => Array
(
[TransPO] => TR11211
[TransactionPrice] => 91.17
)
)
[1] => Array
(
[Order] => Array
(
[PO] => TR11214
[OrderID] => 242856952012
)
[Transaction] => Array
(
[TransPO] => TR11212
[TransactionPrice] => 180.41
)
)
[2] => Array
(
[Order] => Array
(
[PO] => TR11214
[OrderID] => 242856952012
)
[Transaction] => Array
(
[TransPO] => TR11213
[TransactionPrice] => 209.99
)
)
)
The final array I need will look something like this.
Array
(
[Order] => Array
(
[PO] => TR11214
[OrderID] => 242856952012
)
[Transaction] => Array
(
[0] => Array
(
[TransPO] => TR11211
[TransactionPrice] => 91.17
)
[1] => Array
(
[TransPO] => TR11212
[TransactionPrice] => 180.41
)
[2] => Array
(
[TransPO] => TR11213
[TransactionPrice] => 209.99
)
)
)
I can flatten the original array and then use array_unique, but wanted to see if there is a better way to accomplish what I need.
my code:
$myarray = array(
0 => array(
"Order" => array("PO" => "TR11214", "OrderID" => 242856952012),
"Transaction" => array("TransPO" => "TR11211", "TransactionPrice" => 91.17)
),
1 => array(
"Order" => array("PO" => "TR11214", "OrderID" => 242856952012),
"Transaction" => array("TransPO" => "TR11212", "TransactionPrice" => 180.41)
),
2 => array(
"Order" => array("PO" => "TR11214", "OrderID" => 242856952012),
"Transaction" => array("TransPO" => "TR11213", "TransactionPrice" => 209.99)
)
);
print_r(array_unique($myarray, SORT_REGULAR));
If you want to determine how many unique values of the Order element there are in your array, you need to apply array_unique only to the Order elements, which you can do using array_column:
$unique_orders = count(array_unique(array_column($myarray, 'Order'), SORT_REGULAR));
You can process your array using a list of keys which have non-unique values to generate an array, while other keys will have just a single value:
$non_unique_keys = ['Transaction'];
$output = array();
foreach (array_keys($myarray[0]) as $key) {
if (in_array($key, $non_unique_keys)) {
$output[$key] = array_column($myarray, $key);
}
else {
$output[$key] = $myarray[0][$key];
}
}
print_r($output);
Example Output:
Array (
[Order] => Array (
[PO] => TR11214
[OrderID] => 242856952012
)
[Sales Tax] => Array (
[PO] => TR11214
[SalesTaxAmount] => 0
)
[Transaction] => Array (
[0] => Array (
[TransPO] => TR11211
[TransactionPrice] => 91.17
)
[1] => Array (
[TransPO] => TR11212
[TransactionPrice] => 180.41
)
[2] => Array (
[TransPO] => TR11213
[TransactionPrice] => 209.99
)
)
)
Demo on 3v4l.org
array_unique() is intended for single dimensional arrays. If you want to use it on a multi-dimentional array, you should consider using usort() instead. Then you'll need to iterate through the array in reverse manually, searching for duplicates and removing them.

retrieve array two dimension php

i have create array two dimension like this and how i can retrive array two dimension
stdClass Object
(
[error_code] => 0
[error_desc] =>
[data] => Array`enter code here`
(
[0] => stdClass Object
(
[nama_mahasiswa] => STANY SUMARNA
[jenis_kelamin] => L
[tanggal_lahir] => 1996-07-31
[nama_status_mahasiswa] => AKTIF
[nim] => 16304117
[id_periode] => 20161
)
[1] => stdClass Object
(
[nama_mahasiswa] => ADAM
[jenis_kelamin] => L
[tanggal_lahir] => 1996-07-31
[nama_status_mahasiswa] => AKTIF
[nim] => 16304117
[id_periode] => 20161
)
[2] => stdClass Object
(
[nama_mahasiswa] => STANY SUMARNA
[jenis_kelamin] => L
[tanggal_lahir] => 1996-07-31
[nama_status_mahasiswa] => AKTIF
[nim] => 16304117
[id_periode] => 20161
)
)
try following code
lets say $array = main array
$error_code = $array->error_code;
foreach($array->data as $row){
$nama_mahasiswa = $row->nama_mahasiswa;
$jenis_kelamin = $row->jenis_kelamin;
}

PHP Getting Values From Nested Array

I am trying to get the 'name' value from within a 'nested array' I am not sure if thats the correct term in PHP.
Array (
[0] => Array
(
[event] => Array
(
[id] => 28140972
[name] => Northwich v Lincoln United FC
[countryCode] => GB
[timezone] => Europe/London
[openDate] => 2017-03-08T19:45:00.000Z
)
[marketCount] => 24
)
[1] => Array
(
[event] => Array
(
[id] => 28140974
[name] => Viimsi MRJK v Paide Linnameeskond II
[countryCode] => EE
[timezone] => Europe/London
[openDate] => 2017-03-08T17:00:00.000Z
)
[marketCount] => 24
)
}
I am trying to access the 'name' key of every item in the array, but struggling to do it. Any advice?
$arrayOfNames = array_map(function ($item) {
return $item['event']['name'];
}, $yourPreviousArray);
Test case:
>>> print_r($data)
Array
(
[0] => Array
(
[event] => Array
(
[id] => 1
[name] => James
)
)
[1] => Array
(
[event] => Array
(
[id] => 2
[name] => Jim
)
)
)
=> true
>>> array_map(function($item) {
... return $item['event']['name'];
... }, $data)
=> [
"James",
"Jim",
]
>>>
You can do something like this:
foreach ($array as $item) {
echo $item['event']['name'].'<br/>';
}

Categories