How can I search an array for specific values? - php

I need some help with how I can search an array from a search box.
Lets say I search for the $ticker and write BTC
It will then print out:
The last known currency for BTC is 57
I only want it to print out $k3 values.
Appreciate if you could take your time and guide me in the right direction :)
<form method="POST" action="">
<input type="text" name="Searcharray" name="searcharray">
<input type="submit" value="Search" name="searcharray">
</form>
<?php
$ticker = array(
0 => "BTC",
1 => "ETH",
2 => "LTC",
3 => "XMR",
4 => "XRP"
);
$name = array(
0 => "Bitcoin",
1 => "Ethereum",
2 => "Litecoin",
3 => "Monero",
4 => "Ripple"
);
$k1 = array(
0 => 1,
1 => 2,
2 => 3,
3 => 4,
4 => 5
);
$k2 = array(
0 => 11,
1 => 12,
2 => 13,
3 => 14,
4 => 15
);
$k3 = array(
0 => 17,
1 => 27,
2 => 37,
3 => 47,
4 => 57
);
?>

array_search would help - http://php.net/manual/de/function.array-search.php
$index = array_search('BTC', $ticker);
$value = $k3[$index];
Why dont you make such a structure?:
$data = [
'BTC' => [
'name' => 'Bitcoin',
'k1' => 1,
'k2' => 11,
'k3' => 17
], ...
];
then it would be:
$value = $data['BTC']['k3'];

$index = array_search("BTC", $ticker);
if ($index !== FALSE) {
$currency = $k3[$index];
echo "The last known currency of BTC is $currency";
}
But things would be easier if you used a 2-dimensional associative array:
$data = [
"BTC" => ["name" => "Bitcoin", "k1" => 1, "k2" => 11, "k3" => 17],
"ETH" => ["name" => "Ethereum", "k1" => 2, "k2" => 12, "k3" => 27],
...
];
Then you can do:
if (isset($data["BTC"])) {
$currency = $data["BTC"]["k3"];
echo "The last known currency of BTC is $currency";
}

Related

having trouble in transforming a array in php

i have this array
[
[[222] => 1 [333] => 2 [444] => 0],
[[222] => 0 [333] => 2 [444] => 1],
[[222] => 1 [333] => 2 [444] => 0]
]
where [222], [333], [444] are student ids
and 0 means absent
1 means Present
2 means Leave
i want the output will
[ 'student_id' => '222'
'present' => 2 /* total present*/
'absent' => 1 /* total absent*/
'leave' => 0 /* total leave*/
],
[ 'student_id' => '333'
'present' => 0 /* total present*/
'absent' => 0 /* total absent*/
'leave' => 3 /* total leave*/
],
etc.
please give me some soluation in php code
This does exactly what you want, but this site is not a coding service, so i really think you should take the time to understand how i did, and next time try something and share it on your post:
$array = [
[
"222" => 1,
"333" => 2,
"444" => 0
],
[
"222" => 0,
"333" => 2,
"444" => 1
],
[
"222" => 1,
"333" => 2,
"444" => 0
]
];
$results = [];
foreach($array as $k=>$v){
foreach($v as $id=>$value){
if(!isset($results[$id])){
$results[$id] = [
'student_id' => $id,
'present' => 0,
'absent' => 0,
'leave' => 0
];
}
if($value == 0){
$results[$id]['absent']++;
}
if($value == 1){
$results[$id]['present']++;
}
if($value == 2){
$results[$id]['leave']++;
}
}
}
$results = array_values($results);
print_r($results);
This looks like JSON value with there respective keys. You may do that firstly you can arrange these values in PHP ARRAY using foreach then convert that array in JSON.
foreach looping is the best way to access each key/value pair from an array.
foreach($featured as $key => $value){...}
The $key => $value in the foreach loop refers to the key-value pairs in associative arrays, where the key serves as the index to determine the value instead of a number like 0,1,2,... In PHP, associative arrays look like this
$featured = array('student_id' => '111', 'present' => '2', etc.);

How to sum multi-dimensional arrays based on some conditions?

$arr = [ [
'5'=>[
'BG' => 50,
'CH' => 60,
'LG' => 50,
'MT' => 40,
'MO' => 80,
'PH' => 60,
'GE' =>null
]
], [
'6'=>[
'BG' => 90,
'CH' => 60,
'LG' => 60,
'MT' => 50,
'MO' =>null,
'PH' => 50,
'GE' =>null
]
],[
'7'=>[
'BG' => 80,
'CH' => 55,
'LG' => 65,
'MT' => 50,
'MO' =>null,
'PH' => 50,
'GE' => 55
]
]
];
For each id no 5, 6 and 7 I want to sum up the score. CH, PH, MO and LG will always be compulsory to sum up. But after summing up the compulsory items, I want to sum up the other item based on the following condition.
If MO is null, take the best two from BG, MT and GE. If MO is not null or greater than or equal to 0, I want to take the best one from BG, MT or GE.
So the sum up result will look like below:
Array
(
[5] => Array
(
[score] => 300
)
[6] => Array
(
[score] => 310
)
[7] => Array
(
[score] => 305
)
)
I have tried foreach, but I could not solve the problem. How do I solve this problem?
Here is more core way to achieve this, please find inline doc for explanation,
$keys = array_flip(['BG', 'MT', 'GE']); // best of how many keys
$Ckeys = array_flip(['CH', 'PH', 'MO', 'LG']); // compulsory keys
foreach ($arr as $key => $value) {
// use to pass parameters to reduce function during call
$temp[key($value)] = array_reduce($value, function (&$result, $a) use ($keys, $Ckeys) {
// if mo empty then best of two else best of one
$bestHowMany = (!empty($a['MO']) ? 1 : 2);
// fetching best of keys from $keys
$t = array_intersect_key($a, $keys);
// reverse sort and maintains keys
arsort($t);
// fetch top $bestHowMany Values
$largest2 = array_slice($t, 0, $bestHowMany);
// fetch compulsory values from CKeys
$t1 = array_intersect_key($a, $Ckeys);
// sum by merging compulsory and best of $bestHowMany values
return array_sum(array_merge($t1, $largest2));
});
}
working demo.
Output
Array
(
[5] => 300
[6] => 310
[7] => 305
)
Here, we can first add all our three arrays, then subtract based on the conditions, and our codes would look like,
$arr = [[
'5' => [
'BG' => 50,
'CH' => 60,
'LG' => 50,
'MT' => 40,
'MO' => 80,
'PH' => 60,
'GE' => null,
],
], [
'6' => [
'BG' => 90,
'CH' => 60,
'LG' => 60,
'MT' => 50,
'MO' => null,
'PH' => 50,
'GE' => null,
],
], [
'7' => [
'BG' => 80,
'CH' => 55,
'LG' => 65,
'MT' => 50,
'MO' => null,
'PH' => 50,
'GE' => 55,
],
],
];
$sum_arr = array();
foreach ($arr as $key => $arr2) {
foreach ($arr2 as $key2 => $value) {
$sum_arr[$key2]["score"] = array_sum(array_values($value));
$temp = [$value["BG"], $value["MT"], $value["GE"]];
arsort($temp);
if ($value["MO"] === null) {
$sum_arr[$key2]["score"] -= $temp[2];
} elseif ($value["MO"] != null && $value["MO"] >= 0) {
$sum_arr[$key2]["score"] -= $temp[2] + $temp[1];
} else {
continue;
}
}
}
var_dump($sum_arr);
Either there is a bug in my code, which is most likely, or I did not understand the if conditions right, or less likely the desired output might be incorrect. However, it should not be difficult to debug it.
Output
array(3) {
[5]=>
array(1) {
["score"]=>
int(300)
}
[6]=>
array(1) {
["score"]=>
int(310)
}
[7]=>
array(1) {
["score"]=>
int(300)
}
}

PHP Add null to array value if it doesn't exist

I'm generating data arrays and want to add 0/null to a specific month, where no data is present, but been struggling with it for few days.
I'm generating the final dataset array like this
foreach ($patients as $key => $item) {
$labels[] = $item['month'];
usort($labels, "compare_months");
$labels = array_unique($labels);
$chartData[ $item['brand_name'] ]['data'][] =
$item['patientsCount'];
$chartData[ $item['brand_name'] ]['brand_data'] = [
"name" => $item['brand_name'],
"color" => $item['color']
];
}
foreach ($chartData as $item) {
$pointRadius++;
$dataSet[] = [
'label' => $item['brand_data']['name'],
'data' => $item['data'],
'pointRadius' => $pointRadius,
'fill' => false,
'borderWidth' => 1,
'backgroundColor' => "#" . $item['brand_data']['color'],
'borderColor' => "#" . $item['brand_data']['color'],
];
}
$finalData[] = [
'labels' => $labels,
'datasets' => $dataSet
];
Which gives me this json response
[
{
"labels":[
"April",
"May",
"June",
"July"
],
"datasets":[
{
"label":"Medicine 1",
"data":[
1
],
"pointRadius":1,
"fill":false,
"borderWidth":1,
"backgroundColor":"#ea5f2d",
"borderColor":"#ea5f2d"
},
{
"label":"Medicine 2",
"data":[
1,
1,
1
],
"pointRadius":2,
"fill":false,
"borderWidth":1,
"backgroundColor":"#ffb400",
"borderColor":"#ffb400"
},
{
"label":"Medicine 3",
"data":[
1,
1,
2
],
"pointRadius":3,
"fill":false,
"borderWidth":1,
"backgroundColor":"#ff7777",
"borderColor":"#ff7777"
},
{
"label":"Medicine 4",
"data":[
1,
1,
2
],
"pointRadius":4,
"fill":false,
"borderWidth":1,
"backgroundColor":"#64a36f",
"borderColor":"#64a36f"
},
{
"label":"Medicine 5",
"data":[
2
],
"pointRadius":5,
"fill":false,
"borderWidth":1,
"backgroundColor":"#e7e6fc",
"borderColor":"#e7e6fc"
}
]
}
]
As you can see, for some items, the data object only contains 1 value which is wrong, because I need to add zeros to months, where there is no data.
Can this be done in MySQL or is it better to use PHP and how?
EDIT 1
Here is the array I am currently getting.
Array
(
[MEDICINE 1] => Array
(
[April] => 1
)
[MEDICINE 2] => Array
(
[April] => 1
[July] => 2
)
[MEDICINE 3] => Array
(
[April] => 1
[May] => 1
[July] => 2
)
[MEDICINE 4] => Array
(
[May] => 1
[July] => 3
)
[MEDICINE 5] => Array
(
[June] => 2
)
[MEDICINE 6] => Array
(
[July] => 1
)
)
As you can see some medicines have data for only one month and I want to add these months to the medicine array with 0 value, if there is no data.
Add this line after each foreach: if (count($item['data']) < 2) continue;. Because you need skip if length of data is smaller than 2.
foreach ($patients as $key => $item) {
if (count($item['data']) < 2) continue;
$labels[] = $item['month'];
usort($labels, "compare_months");
$labels = array_unique($labels);
$chartData[ $item['brand_name'] ]['data'][] =
$item['patientsCount'];
$chartData[ $item['brand_name'] ]['brand_data'] = [
"name" => $item['brand_name'],
"color" => $item['color']
];
}
foreach ($chartData as $item) {
$pointRadius++;
if (count($item['data']) < 2) continue;
$dataSet[] = [
'label' => $item['brand_data']['name'],
'data' => $item['data'],
'pointRadius' => $pointRadius,
'fill' => false,
'borderWidth' => 1,
'backgroundColor' => "#" . $item['brand_data']['color'],
'borderColor' => "#" . $item['brand_data']['color'],
];
}
$finalData[] = [
'labels' => $labels,
'datasets' => $dataSet
];

how to calculate the sum of same array values in PHP

I have an array like this
$estimate[0]=>
'gear' =>'MMG'
'total' => 315
'efforts' => 9
'afh' => 18
$estimate[1]=>
'gear' =>'MMG'
'total' => 400
'efforts' => 2
'afh' => 6
$estimate[2]=>
'gear' =>'BOO'
'total' => 200
'efforts' => 20
'afh' => 16
$estimate[3]=>
'gear' =>'BOB'
'total' => 250
'efforts' => 20
'afh' => 16
I want to calculate the sum of total, efforts and afh in which gear is same and it will be stored in the another array. Following my coding is working when the array (estimate) size is less than 5.
$calculate = array();
for($et=0;$et<count($estimate);):
if($et==0):
$calculate[$et]['gear'] = $estimate[$et]['gear'];
$calculate[$et]['total'] = $estimate[$et]['total'];
$calculate[$et]['efforts'] = $estimate[$et]['efforts'];
$calculate[$et]['afh'] = $estimate[$et]['afh'];
goto loopend;
endif;
for($cet=0;$cet<count($calculate);$cet++):
if($estimate[$et]['gear'] == $calculate[$cet]['gear']):
$calculate[$cet]['total'] = $calculate[$cet]['total'] + $estimate[$et]['total'];
$calculate[$cet]['efforts'] = $calculate[$cet]['efforts'] + $estimate[$et]['efforts'];
$calculate[$cet]['afh'] = $calculate[$cet]['afh'] + $estimate[$et]['afh'];
goto loopend;
endif;
endfor;
$calculate[$et]['gear'] = $estimate[$et]['gear'];
$calculate[$et]['total'] = $estimate[$et]['total'];
$calculate[$et]['efforts'] = $estimate[$et]['efforts'];
$calculate[$et]['afh'] = $estimate[$et]['afh'];
goto loopend;
loopend:$et++;
endfor;
The coding is not working more than many gears. Sometimes it works. I can't find the issues. Please help me to solve the issues.
You might use array_reduce:
$result = array_reduce($estimate, function($carry, $item) {
if (!isset($carry[$item["gear"]])) {
$carry[$item["gear"]] = $item;
return $carry;
}
$carry[$item["gear"]]["total"] += $item["total"];
$carry[$item["gear"]]["efforts"] += $item["efforts"];
$carry[$item["gear"]]["afh"] += $item["afh"];
return $carry;
});
Demo
As per my comment use foreach loop when your array length is not define
Here is your desired code
<?php
$estimate = array(
"0" => array (
"gear" => 35,
"total" => 30,
"efforts" => 39,
"afh" => 39,
),
"1" => array (
"gear" => 35,
"total" => 30,
"efforts" => 39,
"afh" => 39,
),
"2" => array (
"gear" => 35,
"total" => 30,
"efforts" => 39,
"afh" => 39,
),
);
$gear=0;
$total=0;
$efforts=0;
$afh=0;
foreach ($estimate as $key => $value) {
$gear=$gear+$value['gear'];
$total=$gear+$value['total'];
$efforts=$gear+$value['efforts'];
$afh=$gear+$value['afh'];
}
echo "<pre>";
$result = array('gear' => $gear, 'total' => $total,'efforts' => $efforts,'afh' => $afh);
echo "<pre>";
print_r($result);
you can check the result HERE
<?php
$new_arr = array();
$estimate[0] =array(
'gear' =>'MMG',
'total' => 315,
'efforts' => 9,
'afh' => 18
);
$estimate[1]=array(
'gear' =>'MMG',
'total' => 400,
'efforts' => 2,
'afh' => 6,
);
$estimate[2]=array(
'gear' =>'BOO',
'total' => 200,
'efforts' => 20,
'afh' => 16,
);
$estimate[3]=array(
'gear' =>'BOB',
'total' => 250,
'efforts' => 20,
'afh' => 16,
);
foreach ($estimate as $key => $value) {
$new_arr[$value['gear']] = array(
'total' => (isset($new_arr[$value['gear']]['total']) ? ($new_arr[$value['gear']]['total'] + $value['total']) : $value['total'] ),
'efforts' => (isset($new_arr[$value['gear']]['efforts']) ? ($new_arr[$value['gear']]['efforts'] + $value['efforts']) : $value['efforts'] ),
'afh' => (isset($new_arr[$value['gear']]['afh']) ? ($new_arr[$value['gear']]['afh'] + $value['afh']) : $value['afh'] )
);
}
echo "<pre>";print_r($new_arr);

PHP warning array to string conversion loop inside array key

<?php $student = array(
1 => array(
"firstname" => "first",
"name" => "first",
"group" => "grp01",
"score" => array(
"ASP" => 86,
"PHP" => 79,
"JAVA" => 72,
"HTML" => 96,
"JAVASCRIPT" => 98,
"VBNET" => 66
)
),
2 => array(
"firstname" => "second",
"name" => "second",
"group" => "grp01",
"score" => array(
"ASP" => 80,
"PHP" => 70,
"JAVA" => 71,
"HTML" => 92,
"JAVASCRIPT" => 90,
"VBNET" => 78
)
),
3 => array(
"firstname" => "third",
"name" => "third",
"group" => "grp02",
"score" => array(
"ASP" => 88,
"PHP" => 88,
"JAVA" => 89,
"HTML" => 96,
"JAVASCRIPT" => 98,
"VBNET" => 71
)
) ); ?>
<?php
foreach($student as $std) {
foreach($std as $key => $p){
echo $std[$key];
} } ?>
i am trying to print in echo each student with they average score but right now i am stuck i got a warning about array to string convertion can someone give me some hint how i am suppose to do my loop.
Use PHP-functions to calculate the average for every student, rounded to two digits:
foreach($student as $std) {
$avg = round(array_sum($std['score']) / count($std['score']), 2);
echo $std['name']. ": $avg <br />";
}
see it working: http://codepad.viper-7.com/RBINCd
You are iterating the wrong array, once inside each student you must iterate over the "score", if not you were trying to convert the score array to a string:
foreach($student as $std) {
foreach($std["score"] as $language => $score) {
echo $score;
}
}
The error you are getting comes when you try to echo the "score" portion of the array. As it is itself an array it cannot be echo'd out in this way.
You will need another loop to add up the scores, then get the average outside of it.
Something along the lines of:
foreach($student as $std) {
foreach($std as $key => $p){
if ( $key === 'score'){
$avg = 0;
foreach( $p as $score){
$avg += $score;
}
$avg = ($avg/size_of($p));
}
}
}

Categories