Compare array1 with the arrays of a multidimensional array (Array2 & array3) - php

I want to compare the values of sandra_array with john_array and then with sem_array.
I can compare sandra_array with john_array with:
<?php
$sandra_array = array("soccer" => "10", "basketball" => "20", "atletics" => "40");
$john_array = array("soccer" => "15", "basketball" => "15", "atletics" => "45");
$sem_array = array("soccer" => "5", "basketball" => "10", "atletics" => "50");
$common_sports = array_keys(array_intersect_key($sandra_array, $john_array));
$points_sandra_array = $points_john_array = array_fill_keys($common_sports, 0);
foreach ($common_sports as $common_sport) {
if ($sandra_array[$common_sport] > $john_array[$common_sport]) {
$points_sandra_array[$common_sport]++;
} else if ($sandra_array[$common_sport] < $john_array[$common_sport]) {
$points_john_array[$common_sport]++;
}
}
foreach ($common_sports as $common_sport) {
}
echo "Sandra (", array_sum($points_sandra_array).") vs John (", array_sum($points_john_array).")";
?>
Result
Sandra (1) vs John (2)
I want to have also the results of Sandra against Sem. Like this:
Sandra (1) vs John (2)
Sandra (2) vs Sem(1)
I was thinking about making the following multidimensional array:
$array_other_players = array($john_array,$sem_array);
and then with foreach I will compare first the points of Sandra with the points of John and then with the points of Sem. But I don't know how to do it.
Could you help me with this?

The solution is:
First declare an array containing opponents players' array, like this:
$players_array = array('John' => $john_array, 'Sem' => $sem_array);
And then loop through each opponent player to calculate the final score.
So your code should be like this:
$sandra_array = array("soccer" => "10", "basketball" => "20", "atletics" => "40");
$john_array = array("soccer" => "15", "basketball" => "15", "atletics" => "45");
$sem_array = array("soccer" => "5", "basketball" => "10", "atletics" => "50");
// Declare an array containing opponents players' array
$players_array = array('John' => $john_array, 'Sem' => $sem_array);
// Loop through each opponent player to calculate the final score
foreach($players_array as $opponent_player => $opponent_player_array){
$common_sports = array_keys(array_intersect_key($sandra_array, $opponent_player_array));
$points_sandra_array = $points_opponent_array = array_fill_keys($common_sports, 0);
foreach ($common_sports as $common_sport) {
if ($sandra_array[$common_sport] > $opponent_player_array[$common_sport]) {
$points_sandra_array[$common_sport]++;
} else if ($sandra_array[$common_sport] < $opponent_player_array[$common_sport]) {
$points_opponent_array[$common_sport]++;
}
}
echo "Sandra (". array_sum($points_sandra_array).") vs {$opponent_player} (". array_sum($points_opponent_array) .")<br />";
}
Output:
Sandra (1) vs John (2)
Sandra (2) vs Sem (1)

Related

PHP JSON Multi-dimensional array outputting only 1 result

I have been stumped on this for hours. I need to get the initial key of the array and the id. However I am only getting 1 result returned back.
Below is example code and also here is a link - https://3v4l.org/HdMtA
In short the expected output should be.
key 11111111 id val_somevalue5555
key 2222222 id val_somevalue25
I am only getting one result.
key 11111111 id val_somevalue5555
.
$json = '[{
"11111111": {
"id": "val_somevalue5555",
"customer": {
"32312": {
"name": "john doe"
}
}
},
"2222222": {
"id": "val_somevalue25",
"customer": {
"32312234": {
"name": "jane doe"
}
}
}
}]';
$jsonarr = json_decode($json, true);
$newarr = [];
foreach($jsonarr as $value)
{
$key = key($value);
$newarr[] = ['key' => $key, 'id' => $value[$key]['id']];
}
var_dump($newarr);
Any help would be appreciated not sure if its the format of the json or what.
You are iterating the wrong thing.
Using print_r() to view the contents of the decoded array shows us that the thing you want to iterate over is - in fact - wrapped in another array.
print_r($jsonarr) returns this:
Array
(
[0] => Array
(
[11111111] => Array
(
[id] => val_somevalue5555
[customer] => Array
(
[32312] => Array
(
[name] => jane doe
)
)
)
[2222222] => Array
(
[id] => val_somevalue25
[customer] => Array
(
[32312234] => Array
(
[name] => jane doe
)
)
)
)
)
So, what you have is a JSON object wrapped in JSON array with said object being the only item inside it.
You want to either:
a) Get rid of those [ and ] things at the beginning and the end of your JSON, or... (if you don't have control over that JSON)
b) Iterate the inner object (PHP represents it as associative array):
$jsonarr = json_decode($json, true);
$newarr = [];
foreach($jsonarr[0] as $key => $value) {
$newarr[] = ['key' => $key, 'id' => $value['id']];
}`
var_dump($newarr);
Behold: https://3v4l.org/qCvRd
Change your loop to use the key from the foreach loop itself: Like this
foreach($jsonarr as $key => $value)
{
$newarr[] = ['key' => $key, 'id' => $value[$key]['id']]; //this seems off but what do I know.
}
PHP uses a copy ( or reference?) of the array for Foreach, it can produce some unexpected things to happen. It does some spooky voodoo stuff some times, if you ever try editing the array structure while using reference in foreach such as foreach($var as $k => &$v ) look out. I swear one time it was like phantom items in the array ... lol
You need to change in you json structure and then make necessary changes which I mentioned below
$json = '{
"11111111": {
"id": "val_somevalue5555",
"customer": {
"32312": {
"name": "john doe"
}
}
},
"2222222": {
"id": "val_somevalue25",
"customer": {
"32312234": {
"name": "jane doe"
}
}
}
}';
$jsonarr = json_decode($json, true);
$newarr = [];
foreach($jsonarr as $key=> $value)
{
$newarr[] = ['key' => $key, 'id' => $value['id']];
}
var_dump($newarr);
Are you looking this o/p:
$json = '[{
"11111111": {
"id": "val_somevalue5555",
"customer": {
"32312": {
"name": "john doe"
}
}
},
"2222222": {
"id": "val_somevalue25",
"customer": {
"32312234": {
"name": "jane doe"
}
}
}
}]';
$jsonarr = json_decode($json, true);
$newarr = [];
foreach($jsonarr[0] as $key => $value)
{
//echo "<br />".$key = key($value);
$newarr[] = ['key' => $key, 'id' => $value['id']];
}
var_dump($newarr);
Output:
array(2) {
[0]=>
array(2) {
["key"]=>
int(11111111)
["id"]=>
string(17) "val_somevalue5555"
}
[1]=>
array(2) {
["key"]=>
int(2222222)
["id"]=>
string(15) "val_somevalue25"
}
}
Or you can change the json structure as ankit patel said and follow his code...
Add another foreach to loop the elements of [0] if you will have more than this.
foreach($jsonarr as $value)
{
foreach($value as $key => $val){
$newarr[] = ['key' => $key, 'id' => $val['id']];
}
}
Result
array(2) {
[0]=>
array(2) {
["key"]=>
int(11111111)
["id"]=>
string(17) "val_somevalue5555"
}
[1]=>
array(2) {
["key"]=>
int(2222222)
["id"]=>
string(15) "val_somevalue25"
}
}
Test here

How to combine objects to array without removing duplicates in PHP

I have 3 objects and I want them to combine into 1 array. There are duplicate property names in objects, but I want them too (with renames property name). How can I do that?
$object1 = {
"id": "10",
"unit_number": "12565"
},
$object2 = {
"id": "20",
"full_name": "Lorem Ipsm"
},
$object3 = {
"id": "30",
"phone": "123456789"
}
I want the output like,
array = (
"id1" => "10",
"unit_number" => "12565",
"id2" => "20",
"full_name" => "Lorem Ipsm",
"id3" => "30",
"phone" => "123456789"
);
I have tried to assign them to one array like,
$arr = array();
$arr['obj1'] = $object1;
$arr['obj2'] = $object2;
$arr['obj3'] = $object3;
Now I thought of doing a foreach, but I am stuck. My actual object is too big. So there are many duplicates. Not just this one.
I think you can achieve this using below code,
$object1 = (object) ['id' => '10', "unit_number"=> "12565", "name" => 'Test name'];
$object2 = (object) ['id' => '20', "full_name"=> "Lorem Ipsm"];
$object3 = (object) ['id' => '30', "phone"=> "123456789", "name" => "test name 1"];
$array1 = (array) $object1;
$array2 = (array) $object2;
$array3 = (array) $object3;
function array_merge_dup_keys() {
$arrays = func_get_args();
$data = array();
foreach ($arrays as $a) {
foreach ($a as $k => $v) {
$key1 = check_key_exists($k,$data);
$data[$key1] = $v;
}
}
return $data;
}
function check_key_exists($key,$array,$loop_count=1)
{
if(array_key_exists ( $key , $array ))
{
$val = explode('_',$key);
$count = isset($val[1]) ? $val[1] : $loop_count;
$start_key = isset($val[0]) ? $val[0] : $key;
$key = $start_key.'_'.$loop_count;
$key = check_key_exists($key,$array,$count+1);
}
return $key;
}
$data = array_merge_dup_keys($array1 ,$array2,$array3);
The output ($data) of above code will be,
Array
(
[id] => 10
[unit_number] => 12565
[name] => Test name
[id_1] => 20
[full_name] => Lorem Ipsm
[id_2] => 30
[phone] => 123456789
[name_1] => test name 1
)
Maybe something like this? (untested, possible typos/syntax errors...)
// this looks like json, not PHP
// "object1": {
// "id": "10",
// "unit_number": "12565"
// },
// "object2": {
// "id": "20",
// "full_name": "Lorem Ipsm"
// },
// "object3": {
// "id": "30",
// "phone": "123456789"
// }
// here is a php array for that data
$objArray = array(
"object1" => array( "id"=>"10", "unit_number"=>"12565"),
"object2" => array( "id"=>"20", "full_name"=>"Lorem Ipsm"),
"object3" => array( "id"=>"30", "phone"=>"123456789")
);
$newArray = array();
foreach( $objArray as $key=>$value)
{
// the the id "append"
$idAppend = substr($key, strlen("object"));
foreach($value as $subkey=>$subvalue)
{
$newkey = $subkey;
if ( strcmp($subkey, "id") == 0 ) // it is the id string
{
$newkey = $subkey.$idAppend;
}
$newArray[$newkey] = $subvalue;
}
}

foreach doesnt do loops for my search [duplicate]

This question already has answers here:
How can I check if an array contains a specific value in php? [duplicate]
(8 answers)
Closed 7 years ago.
i have a foreach where i want to compare some strings from two arrays
output of variable $count_land
Array
(
["US"] => 186
["DE"] => 44
["BR"] => 15
["FR"] => 3
["other"] => 7
)
Other array:
$all_lands_array = ["CN", "DE", "US", "EU", "RU", "BR", "GB", "NL", "LU", "other", "IT"];
what i need is every key in the $all_lands_array that have the same letters from the $count_land array and save them in another variable
that means i need to get US, DE, BR, FR, other and save them in a new variable
i hope you understand what i need :)
this is my loop but it doesnt find any match.. but why?
foreach($all_lands_array as $lands){
if($lands == $count_land)
return "match";
else
return "no match!";
}
Because you just loop through one array and then check the value against the whole other array.
Checking for country codes:
$count_land = array
(
"US" => 186,
"DE" => 44,
"BR" => 15,
"FR" => 3,
"other" => 7
);
$all_lands_array = array("CN", "DE", "US", "EU", "RU", "BR", "GB", "NL", "LU", "other", "IT");
$matches = array();
foreach($count_land as $key => $val){
if(in_array($key, $all_lands_array)){
$matches[$key] = $val; // add matches to array;
}else{
// do nothing
}
}
print_r($matches);die;
returns:
Array ( [US] => 186 [DE] => 44 [BR] => 15 [other] => 7 )
You have to save the countries in a variable as an array and use in_array to check if an element is in that array:
$found = array();
$countries = array_keys($count_land); //stores: US,DE..etc
foreach($all_lands_array as $country){
if(in_array($country, $countries)){ //if a country name is found in $countries array,
//OPTIONALLY: exclude 'other'
//if(in_array($country, $countries) && $country !='other')
$found[] = $country; //store them in the $found variable
}
}
Test
$count_land = array('US'=>1,'DE'=>1,'BR'=>1,'FR'=>1,'other'=>1);
$all_lands_array = ["CN", "DE", "US", "EU", "RU", "BR", "GB", "NL", "LU", "other", "IT"];
var_dump($found);
array(4) {
[0]=>
string(2) "DE"
[1]=>
string(2) "US"
[2]=>
string(2) "BR"
[3]=>
string(5) "other"
}

creating nested associative array from json code

I am creating an associative array from a json code so that i can use in my curl code that connects to an API. Now it seems like the associative array outputted is incorrect. I would like to format it correctly, but now I get message an error saying the array is incorrect.
The json code:
{
"payment": [
{
"clientCorrelator": "54321",
"endUserId": "tel:+16309700001",
"merchantCode": "01234",
"merchantPin": "1234",
"merchantNumber": "tel:+16309700001",
"notifyURL": "http://example.com/notifyURL",
"paymentAmount": {
"chargingInformation": [
{
"amount": "10",
"currency": "USD",
"description": "AlienInvadersGame"
}
],
"chargingMetaData": [
{
"onBehalfOf": "Example Games Inc",
"purchaseCategoryCode": "Game",
"channel": "WAP",
"taxAmount": "0"
}
],
"referenceCode": "REF-12345",
"transactionOperationStatus": "Charged"
}
}
]
}
The php code to build the array:
jasondata = file_get_contents("payment.json");
$json = json_decode($jasondata, true);
$payment = ($json['payment']) ;
print_r($payment);
The output:
Array ( [0] => Array ( [clientCorrelator] => 54321 [endUserId] => tel:+16309700001 [merchantCode] => 01234 [merchantPin] => 1234 [merchantNumber] => tel:+16309700001 [notifyURL] => http://example.com/notifyURL [paymentAmount] => Array ( [chargingInformation] => Array ( [0] => Array ( [amount] => 10 [currency] => USD [description] => AlienInvadersGame ) ) [chargingMetaData] => Array ( [0] => Array ( [onBehalfOf] => Example Games Inc [purchaseCategoryCode] => Game [channel] => WAP [taxAmount] => 0 ) ) [referenceCode] => REF-12345 [transactionOperationStatus] => Charged ) ) )
My main goal is to remove the [0] indexes without messing up the array. please assist
instead of $payment = ($json['payment']);
change that to $payment = reset($json['payment']);
However if there are multiple entries under payment, then you should just loop over them like:
foreach($json['payment'] as $payment){
print_r($payment);
}
The loop also would work if there was any number of elements under payment, so not just multiple.
more or less safe function
$payment = json_decode($str, true);
function RemoveZeroIndex(&$arr) {
foreach($arr as $key => &$item) { // walk array
if (is_array($item) && // if array
(count($item) === 1) && // with one item
isset($item[0])) // and numeric index
$item = $item[0]; // shift it
if (is_array($item))
RemoveZeroIndex($item); // call recursively
}
}
RemoveZeroIndex($payment);
print_r($payment);
In addition to Jonathan Khun.
For your nested arrays you just do the same. Reset the internal pointer of that array.
<?php
$jasondata = '{
"payment": [
{
"clientCorrelator": "54321",
"endUserId": "tel:+16309700001",
"merchantCode": "01234",
"merchantPin": "1234",
"merchantNumber": "tel:+16309700001",
"notifyURL": "http://example.com/notifyURL",
"paymentAmount": {
"chargingInformation": [
{
"amount": "10",
"currency": "USD",
"description": "AlienInvadersGame"
}
],
"chargingMetaData": [
{
"onBehalfOf": "Example Games Inc",
"purchaseCategoryCode": "Game",
"channel": "WAP",
"taxAmount": "0"
}
],
"referenceCode": "REF-12345",
"transactionOperationStatus": "Charged"
}
}
]
}';
$json = json_decode($jasondata, true);
$payment = reset($json['payment']);
$payment['paymentAmount']['chargingInformation'] = reset($payment['paymentAmount']['chargingInformation']);
$payment['paymentAmount']['chargingMetaData'] = reset($payment['paymentAmount']['chargingMetaData']);
echo "<pre>";
print_r($payment);
?>

Arrange the array in table format

This is my array and I want to set this array in table format and I want to set first row as show below:
$_tierPrices = Array
(
Array
(
"price_qty" => "4",
"price" => "143.00",
"savePercent" => "8"
),
Array
(
"price_qty" => "12",
"price" => "133.0000",
"savePercent" => "15"
),
Array
(
"price_qty" => "20",
"savePercent" => "18",
"price" => "128.0000"
),
Array
(
"price_qty" => "40",
"savePercent" => "21",
"price" => "123.0000"
)
);
I want to set this array value in table format as shown below
This is my table row:
4 | 12 | 20 | 40 |
I need this:
4 - 11 | 12 - 19 | 20 - 39 | 40+ |
Please advise.
Try this:
Tier Price Array
<?php
$_tierPrices = array (
array
(
"price_qty" => "4",
"price" => "143.00",
"savePercent" => "8"
),
array
(
"price_qty" => "12",
"price" => "133.0000",
"savePercent" => "15"
),
array
(
"price_qty" => "20",
"savePercent" => "18",
"price" => "128.0000"
),
array
(
"price_qty" => "40",
"savePercent" => "21",
"price" => "123.0000"
)
);
?>
Tier Price Table
<table>
<tr><td>Header</td></tr>
<?php $_qtyRow = '<tr>'; ?>
<?php $_priceRow = '<tr>'; ?>
<?php $_saveRow = '<tr>'; ?>
<?php
$size = count($_tierPrices);
foreach($_tierPrices as $index => $_tierPrice) {
if($index < $size-1) {
$_qty = $_tierPrice['price_qty'] . ' - ' . ($_tierPrices[$index+1]['price_qty'] - 1);
} else {
$_qty = $_tierPrice['price_qty'] . '+';
}
$_qtyRow .= '<td>'.$_qty.'</td>';
$_priceRow .= '<td>'.$_tierPrice['price'].'</td>';
$_saveRow .= '<td>'.$_tierPrice['savePercent'].'</td>';
}
$_qtyRow .= '</tr>';
$_priceRow .= '</tr>';
$_saveRow .= '</tr>';
echo $_qtyRow;
echo $_priceRow;
echo $_saveRow;
?>
<tr><td>Footer</td></tr>
</table>
I hope this will help.
I don't know what you have in $_tierPrices so i am giving you an example by for some other data.
$arr = array('4','12','20','40'); //suppose you have array like this
$end = end($arr); //We need to find last element of the array to show like 40+
for($i=0;$i<count($arr);$i++){
if($arr[$i] != $end){
echo $arr[$i]."-".($arr[$i+1]-1)." | ";
} else{
echo $arr[$i]."+";
}
}
Output will be like
4-11 | 12-19 | 20-39 | 40+
<?php
echo "<table><tr>";//opening the table
$first_iteration = FALSE;
foreach ($_tierPrices as $value)
{
if (!$first_iteration)//code that only runs on the first iteration
{
$first_iteration = TRUE;
$buffer_value = $value;
}
else {//code that runs after the first iteration
$buff = ((integer)$value)-1;//calculation1 value previous
$output = $buffer_value."-".$buff;
echo "<td>".$output."</td>";
$buffer_value = $value;
}
}
echo "<td>".$buffer_value."+</td>";
echo "</tr></table>";//closing the table
?>
let me know if that worked for you :)

Categories