How to compare three values in a array and merge? - php

How can i merge array with the same value?
I have three array which are $participants, $conferance_participants and $contacts
i want to compare values with this three array and merge
for example :
if $participants['calleridnum'] == $conferance_participants['uid'] == $contacts['name']
i want the output to be like this :
Array
(
[0] => Array
(
[calleridnum] => 1
[test] => yay
[uid] => 1
[channel] => deze
[name] => 1
[limit] => 1
)
)
this is my code so far:
<?php
$participants = [
[ 'calleridnum' => 1,
'test' => 'yay'
]
];
$conferance_participants = [
[ 'uid' => 1,
'test' => 'yay2',
'channel' => 'deze'
]
];
$contacts = [
[ 'name' => 1,
'test' => 'yay2',
'limit' => 1
]
];
foreach ($participants as $participant=>$p) {
foreach ($conferance_participants as $conferance_participant=>$c) {
foreach ($contacts as $contact=>$cs) {
if (($p['calleridnum'] == $c['uid']) && ($c['uid'] == $cs['name'])) {
foreach ( $c as $key=>$val ) {
if (!isset($p[$key])) {
$participants[$participant][$key] = $val;
}
}
}
}
}
}
print_r( $participants );
?>

Try to call array_merge() , but you still have to consider the different values with the same key (eg. the values of key 'test' )
if (($p['calleridnum'] == $c['uid']) && ($p['uid'] == $c['name'])) {
$participants[$participant] = array_merge(
$participants[$participant],
$conferance_participants[$conferance_participant],
$contacts[$contact]
);
}

Related

Matching multidimensional array value with two values from other array in php

I have array name $main_array
$main_array = [
[
'product_id' => '1',
'values' => '1"'
],
[
'product_id' => '4',
'values' => '1"'
],
[
'product_id' => '4',
'values' => 'blue'
],
[
'product_id' => '5',
'values' => 'blue'
]
];
I want to check values from other array
$check_array = [
'1"','blue'
];
Find product_id where 1" && blue both matching
Expected output ::
$output = [
[
'product_id' => '4',
'values' => '1"'
],
[
'product_id' => '4',
'values' => 'blue'
]
];
You could use an array to store matching elements using the product id as key.
$include = [] ;
foreach ($main_array as $key => $item) {
// if values match to $check_array
if (in_array($item['values'], $check_array)) {
// store using product id as key
$pid = $item['product_id'] ;
$include[$pid][] = $key;
}
}
// Filter to keep only items that match with all conditions
$include = array_filter($include, function($a) use ($check_array) {
return count($a) == count($check_array) ;
}) ;
$include = reset($include) ; // Get the first
// Recreate final array :
$out = [] ;
foreach ($include as $elem) {
$out[] = $main_array[$elem] ;
}
print_r($out);
Will outputs :
Array
(
[0] => Array
(
[product_id] => 4
[values] => 1"
)
[1] => Array
(
[product_id] => 4
[values] => blue
)
)
You may use nested foreach cycles. Supposed that $check_array containes two fields, you can write a code like this:
$output = array();
$match_array = array();
//check the first field correspondence
foreach ($main_array as $key1=>$sub_main) {
foreach ($sub_main as $key2=>$item) {
if ($check_array[0] == $item['values']) {
$match_array[] = $item['product_id'];
}
}
}
//try to match the second field
foreach ($main_array as $key1=>$sub_main) {
foreach ($sub_main as $key2=>$item) {
if ($check_array[1] == $item['values']) {
if (in_array($item['product_id'], $match_array) {
$output[] = array($item['product_id'], $check_array[1]);
$output[] = array($item['product_id'], $check_array[2]);
}
}
}
}

Selecting value from array with a range?

I've an array on php that will return a lot of keys->values, like this:
Array
[0] => Array
(
[value] => 405
[information] => some information1
)
[1] => Array
(
[value] => 500
[information] => some information2
)
[2] => Array
(
[value] => 700
[information] => some information3
)
the values are numbers, i need to collect all the values, check the first one that will be >= $determinedvalue and then return the value "information" for this exactly array, is this even possible? I know i can do this if i create a temp table on my database, but i dont want to.
To be more clearly, when my value is "430" it will return me "some information2".
I've searched a lot on google but by now i dont know if this is even possible.
Appreciate any help.
This is a sample on how to do that. Comments in code can be used to explain the execution.
// Sample Array
$arr = array(
array
(
"value" => 405,
"information" => "some information1"
),
array
(
"value" => 500,
"information" => "some information2"
),
array
(
"value" => 700,
"information" => "some information3"
)
);
// Sample Number
$numberToCheck = 430;
// Sub Array To Assign
$subArray = array();
// Loop Through Outer Array
for ( $i = 0; $i < sizeof($arr); $i++)
{
// If Value In Array > Number Check
if ( $arr[$i]['value'] >= $numberToCheck )
{
$subArray = $arr[$i]; // Assign Sub Array
$i = sizeof($arr); // This is Used to Exit For Loop
}
}
print_r($subArray); // Print
Working runnable code: https://tech.io/snippet/QJ93AwV
Code snippent with comments:
<?php
/**
* Helper class for stable sort alogithms
* #see https://github.com/vanderlee/PHP-stable-sort-functions
* Class StableSort
*/
class StableSort
{
static public function usort(array &$array, $value_compare_func)
{
$index = 0;
foreach ($array as &$item) {
$item = array($index++, $item);
}
$result = usort($array, function ($a, $b) use ($value_compare_func) {
$result = call_user_func($value_compare_func, $a[1], $b[1]);
return $result == 0 ? $a[0] - $b[0] : $result;
});
foreach ($array as &$item) {
$item = $item[1];
}
return $result;
}
}
$array = [
// added for test sorting
[
'value' => 9999,
'information' => 'some information-1',
],
[
'value' => 1200,
'information' => 'some information0',
],
// \added for test sorting
[
'value' => 405,
'information' => 'some information1',
],
// added for test sorting stability
[
'value' => 405,
'information' => 'some information1.2',
],
[
'value' => 405,
'information' => 'some information1.1',
],
// \added for test sorting stability
[
'value' => 500,
'information' => 'some information2',
],
[
'value' => 700,
'information' => 'some information3',
],
];
// sort array
$determinedvalue = 430;
StableSort::usort($array, function ($item1, $item2) {
if ($item1['value'] == $item2['value']) return 0;
return $item1['value'] < $item2['value'] ? -1 : 1;
});
// then select the first element by condition
$res = null;
foreach($array as $v) {
if($v['value'] >= $determinedvalue) {
$res = $v['information'];
break;
}
}
// for testing
print $res;
$number = 430;
$array = Array
[0] => Array
(
[value] => 405
[information] => some information1
)
[1] => Array
(
[value] => 500
[information] => some information2
)
[2] => Array
(
[value] => 700
[information] => some information3
)
$firstArray = $array[0];
$secondArray = $array[1];
$threeArray = $array[2];
function selectValueFromArrayRange ($number, $start, $end, $value, $infomation)
{
$startValue = $start[$value];
$endValue = $end[$value];
if ( in_array($number, range($startValue, $endValue)) ) {
return $end[$infomation];
}
}
selectValueFromArrayRange($number, $firstArray, $secondValue, 'value', 'infomation')

Multidimensional Array delete duplicated key values with condition

I have an Array Like this:
$ratesData = [
1 => [
'id' => 1,
'amount' => 2
],
0 => [
'id' => 1,
'amount' => 1
],
2 => [
'id' => 1,
'amount' => 3
],
3 => [
'id' => 2,
'amount' => 2
]
];
I want to keep the duplicated id arrays with cheapest amount, the result will be like this:
[
0 => [
'id' => 1,
'amount' => 1
],
1 => [
'id' => 2,
'amount' => 2
]
]
I have a code that works with this problem, but I'm searching an elegant way to accomplish this without all this loops:
foreach($ratesData as $firstLoopKey => $firstLoopValue) {
foreach($ratesData as $secondLoopKey => $secondLoopValue) {
if($firstLoopValue['id'] === $secondLoopValue['id'] && $firstLoopKey != $secondLoopKey ) {
if ($ratesData[$secondLoopKey]['total_amount'] > $ratesData[$firstLoopKey]['total_amount']) {
$deleteElements[] = $secondLoopKey;
}
}
}
}
if (isset($deleteElements)) {
foreach ($deleteElements as $element) {
unset($ratesData[$element]);
}
}
$ratesData = array_values($ratesData);
return $ratesData;
You can sort by amount descending and then extract the array indexing by id which will eliminate the duplicates with the lowest amount overwriting the higher:
array_multisort(array_column($ratesData, 'amount'), SORT_DESC, $ratesData);
$ratesData = array_column($ratesData, null, 'id');
Yields:
Array
(
[1] => Array
(
[id] => 1
[amount] => 1
)
[2] => Array
(
[id] => 2
[amount] => 2
)
)
I always like having the key the same as a unique id to make array access/sorting easier, but you can re-index if needed:
$ratesData = array_values($ratesData);
Some simple solution:
// your source array
$ratesData = [];
// result array
$filtered = [];
foreach ($ratesData as $v) {
$id = $v['id'];
// if this is `$id`, which is not in `$filtered` yet
// or value of `$filtered[$id]['amount']` is greater then current `$v`
// then replace `$filtered[$id]` with current `$v`
if (!isset($filtered[$id]) || $filtered[$id]['amount'] > $v['amount']) {
$filtered[$id] = $v;
}
}
echo'<pre>',print_r(array_values($filtered)),'</pre>';
Another good solution
$uniqueRates = [];
foreach ($ratesData as $rateData) {
$key = $rateData['id'];
if (!\array_key_exists($key, $uniqueRates) ||
$rateData['total_amount'] < $uniqueRates[$key]['total_amount']
) {
$uniqueRates[$key] = $rateData;
}
}
return array_values($uniqueRates);

Compare element in array and loop through each php

I want to compare a value of data to a list of element which I had retrieved from php array(decoded json).
First,
This is the first array:
Array1
(
[0] => Array
(
[member_id] => 3
[member_card_num] => 2013011192330791
[member_barcode] => 2300067628912
)
[1] => Array
(
[member_id] => 4
[member_card_num] => 2328482492740000
[member_barcode] => 3545637000
)
[2] => Array
(
[member_id] => 2
[member_card_num] => 40001974318
[member_barcode] => 486126
)
[3] => Array
(
[member_id] => 1
[member_card_num] => 91001310000057698
[member_barcode] => 000057698
)
)
This is the second Array:
Array2
(
[0] => Array
(
[member_id] => 2
[member_card_num] => 40001974318
[member_barcode] => 486126
)
)
Second,
I had retrieved the (member_barcode) which I required.
Here is the code:
For Array1:
foreach ($decode1 as $d){
$merchant_barcode = $d ['member_barcode'];
echo $merchant_barcode;
}
For Array2:
foreach ($decode2 as $d2){
$user_barcode = $d2 ['member_barcode'];
echo $user_barcode;
}
Then,
I get this output():
For Array1(merchant_barcode):
2300067628912
3545637000
486126
000057698
For Array2(user_barcode):
486126
The question is, I would to check and compare whether the user_barcode in Array2(486126) is exist/match to one of the merchant_barcode in Array1.
This is my code,
but it only compare the user_barcode in Array2 to the last element(000057698) in Array1,
I want it to loop through each n check one by one. How can I do that?
public function actionCompareBarcode($user_barcode, $merchant_barcode){
if(($user_barcode) == ($merchant_barcode)){
echo "barcode exist. ";
}
else{
echo "barcode not exist";
}
}
In this case, the output I get is "barcode not exist", but it should be "barcode exist".
Anyone can help? Appreciate that. Im kinda new to php.
You could use a nested loop like:
foreach ($decode2 as $d2)
{
$user_barcode = $d2 ['member_barcode'];
foreach ($decode1 as $d)
{
$merchant_barcode = $d ['member_barcode'];
if ($merchant_barcode == $user_barcode)
{
echo "Match found!";
}
else
{
echo "No match found!";
}
}
}
<?
$a = array(
array(
'member_id' => 3,
'member_card_num' => '2013011192330791',
'member_barcode' => '2300067628912',
),
array(
'member_id' => 4,
'member_card_num' => '2328482492740000',
'member_barcode' => '3545637000',
),
array(
'member_id' => 2,
'member_card_num' => '40001974318',
'member_barcode' => '486126',
),
array(
'member_id' => 1,
'member_card_num' => '91001310000057698',
'member_barcode' => '000057698',
)
);
$b = array(
array(
'member_id' => 2,
'member_card_num' => '40001974318',
'member_barcode' => '486126',
)
);
array_walk($a, function($item) use($b) {
echo ($b['0']['member_barcode'] == $item['member_barcode'] ? "found" : NULL);
});
?>
I'd use array_uintersect() to calculate if those multidimensional arrays have a common element:
<?php
$a = array(
array(
'member_id' => '3',
'member_card_num' => '2013011192330791',
'member_barcode' => '2300067628912',
),
array(
'member_id' => '2',
'member_card_num' => '40001974318',
'member_barcode' => '486126',
)
);
$b = array(
array(
'member_id' => '2',
'member_card_num' => '40001974318',
'member_barcode' => '486126',
)
);
$match = array_uintersect($a, $b, function($valueA, $valueB) {
return strcasecmp($valueA['member_barcode'], $valueB['member_barcode']);
});
print_r($match);
Try calling that method as you are looping through Array1 and comparing the user_barcode to every value
You can compare two array this way too:
$per_arr = array();
$permissions = array()
foreach ($per_arr as $key => $perms) {
if(isset($permissions[$key]['name'])){
echo $per_arr[$key]['name']; //matched data
}else{
echo $per_arr[$key]['name']; //not matched data
}
}

PHP: Post array to functions and create multidimensional array

I need to create a similar array to this:
$need = Array(
"smsSend" => Array(
"account" => Array(
"user" => 123,
"password" => "xxxxxx",
"profile" => 123456
)
),
"smsConfig" => Array
(
"region" => Array
(
"locale" => "es_ES",
"timezone" => "America/Bogota"
),
"send" => Array
(
"from" => "9:00:00",
"to" => "21:00:00"
),
"sms" => Array
(
"channel" => "SMS",
"from" => "LINIO",
)
),
"templateConfig" => Array
(
"template" => Array
(
"postpago" => 1111,
"prepago" => 0010,
"notificar" => 1112
)
),
"fieldsConfig" => Array
(
"fields" => Array
(
"nombre" => "firstname",
"carrier" => "nome_transportadora",
"track" => "track",
"cantidad" => "total_depois_de_impostos"
)
),
"serverConfig" => Array
(
"test" => "http://miportal",
"prod" => "",
"mode" => "test",
"adapter" => "curl",
"type" => "post",
"telephone" => "12345"
),
"fields" => Array
(
"sms" => Array
(
"address" => "mobile_phone"
),
"email" => Array
(
"address" => "email_cliente"
)
)
);
From this arrangement to receive from $_POST:
$post = Array(
"smsSend" => Array(
"account" => Array(
"user:123",
"password:xxxxxx",
"profile:123456"
)
),
"smsConfig" => Array
(
"region" => Array
(
"locale:es_ES",
"timezone:America/Bogota"
),
"send" => Array
(
"from:9:00:00",
"to:21:00:00"
),
"sms" => Array
(
"channel:SMS",
"from:LINIO",
)
),
"templateConfig" => Array
(
"template" => Array
(
"postpago:1111",
"prepago:0010",
"notificar:1112"
)
),
"fieldsConfig" => Array
(
"fields" => Array
(
"nombre:firstname",
"carrier:nome_transportadora",
"track:track",
"cantidad:total_depois_de_impostos"
)
),
"serverConfig" => Array
(
"test:http://miportal",
"prod:",
"mode:test",
"adapter:curl",
"type:post",
"telephone:12345"
),
"fields" => Array
(
"sms" => Array
(
"address:mobile_phone"
),
"email" => Array
(
"address:email_cliente"
)
)
);
The problem is the cycle to assemble items of the parent, I use tree function to create levels:
function createLevel1($array_data) {
$array_push = array();
foreach ($array_data as $key_l1 => $elem_l1) {
array_push($array_push[$key_l1], "");
createLevel2($elem_l1, $array_push, $key_l1);
// print_r($resl1);
}
return $array_push;
}
function createLevel2($elemento_array, $push_array, $parent_key) {
foreach ($elemento_array as $key_l2 => $elem_l2) {
if (is_array($elem_l2)) {
$push_array[$parent_key][$key_l2] = "";
createLevel3($elem_l2, $push_array, $parent_key, $key_l2);
} else {
$items = explode("::", $elem_l2);
$push_array[$parent_key][$items[0]] = $items[1];
}
}
return $push_array;
}
function createLevel3($elemento_array, $push_array, $parent_key, $parentl2_key) {
$push_array[$parent_key][$parentl2_key] = "";
foreach ($elemento_array as $key_l3 => $elem_l3) {
if (is_array($elem_l3)) {
createLevel3($elem_l3, $push_array, $parent12_key, $key_l3);
} else {
$items = explode("::", $elem_l3);
$push_array[$parent_key][$parentl2_key][$items[0]] = $items[1];
}
}
return $push_array;
}
$parameter = $_POST['postData'];
#$info = createLevel1($parameter);
print_r($parameter);
The value of the parameter is array $post, the problem is when I print the result $info like this, the option is blank.:
Array
(
[smsSend] =>
[smsConfig] =>
[templateConfig] =>
[fieldsConfig] =>
[serverConfig] =>
[fields] => Array
(
[sms] =>
[email] =>
)
)
$need = array();
foreach ($post as $key => $value) {
if (is_array($value)) {
$need[$key] = $value;
foreach ($value as $key2 => $value2) {
if (is_array($value2)) {
foreach ($value2 as $key3 => $value3) {
if (is_array($value3)) {
} elseif (strpos($value3, ':') !== FALSE) {
$tmp3 = explode(':', $value3);
$need[$key][$key2][$tmp3[0]] = $tmp3[1];
unset($need[$key][$key2][$key3]);
}
}
} elseif (strpos($value2, ':') !== FALSE) {
$tmp2 = explode(':', $value2);
$need[$key][$tmp2[0]] = $tmp2[1];
unset($need[$key][$key2]);
}
}
}
}
I have wrote this code. I think it is working. But issue is there. when i use explode it divide http://miportal.com also. try another method like strstr. Try it with recursive function.

Categories