Let's say I have this array in PHP
Array(
[0] => Array
(
[DLVRD] => 2
[FAILED] => 1
[REJECT] => 4
[QUEUED] => 5
)
[1] => Array
(
[DLVRD] => 5
[FAILED] => 0
[REJECT] => 3
[QUEUED] => 2
)
[2] => Array
(
[DLVRD] => 3
[FAILED] => 0
[REJECT] => 1
[QUEUED] => 3
)
)
And I want to do is to have result something like this
Array
(
[DLVRD] => 10
[FAILED] => 1
[OTHERS] => 8
)
Currently my PHP code is like this:
foreach($GetTelcosRevenue as $telco) {
if($telco['dr_detail'] == 'DLVRD') {
$TelcoRevenue .="DLVRD:".$telco['TheTraffics'].",";
}
else if($telco['dr_detail'] == 'FAILED') {
$TelcoRevenue .="FAILED:".$telco['TheTraffics'].",";
}
else {
?????
}
}
}
I have tried to put $Others += $telco['TheTraffics'] and other hacks but I still got wrong result. Thanks for any help
You can do, by this way :
$sum = array();
foreach ($array as $k=>$sub) { // $array is your question array
foreach ($sub as $id=>$value) {
$sum[$id]+=$value;
}
}
print_r($sum);
Related
I'm trying to use the foreach loop to loop over multiple arrays and separate values into 2 groups determined by an ID value on each array and then echo them, eventually to a table.
So for example I have the given 2D array as follows: (I have used just 3 as an example but there will be more in reality)
Array
(
[results] => Array
(
[numbpeople] => 3
[people] => Array
(
[0] => Array
(
[name] => bert
[mainId] => 2
[beens] => 0
[coins] => 8
[total] => 3
[ammount] => 2
[place] => 15
[type] => 0
)
[1] => Array
(
[name] => bungle
[mainId] => 1
[beens] => 0
[coins] => 4
[total] => 0
[ammount] => 10
[place] => 13
[type] => 0
)
[2] => Array
(
[name] => fred
[mainId] => 2
[beens] => 0
[coins] => 3
[total] => 1
[ammount] => 8
[place] => 11
[type] => 0
)
)
)
)
I try the following code but it does not work the way its intended.
//foreach ($data['results']['people'] as $pValue) {
foreach ($data['results']['people'] as $Key => $pValue) {
$numPeople = $data["results"]["numbpeople"]; //[$i];
if($numPeople>-1)
{
$MainId1="";
$MainId2="";
// set up header
echo "<strong>People:<br>name, beens, coins, total.</strong><br>";
echo "<br>";
// calculate who's got what?
$i=0;
while($i<$numPeople)
{
$pname[$i]=$pValue["name"][$i];
$pmainId[$i]=$pValue["mainId"][$i];
$pbeens[$i]=$pValue["beens"][$i];
$pcoins[$i]=$pValue["coins"][$i];
$ptotal[$i]=$pValue["total"][$i];
if(!stristr($pValue["mainId"],"1") && !stristr($pValue["mainId"],"2")) {
if($pmainId[$i]!=$MainId1 && $MainId1=="") {
$p1Name=$pname[$i]; // people1 name
$p1Beens=$pbeens[$i]; // people1 beens
$p1Coins=$pcoins[$i]; // people1 coins
$p1Total=$ptotal[$i]; // people1 total
}
if($pmainId[$i]!=$MainId1 && $MainId1!="" && $MainId2=="") {
$p2Name=$pname[$i]; // people2 name
$p2Beens=$pbeens[$i]; // people2 beens
$p2Coins=$pcoins[$i]; // people2 coins
$p2Total=$ptotal[$i]; // people2 total
}
// Id
if($pmainId[$i]!=$MainId1 && $MainId1=="") {
$MainId1=$pmainId[$i];
}
if($pmainId[$i]!=$MainId1 && $MainId1!="" && $MainId2=="") {
$MainId2=$pmainId[$i];
}
} else {
$MainId1="1";
$MainId2="2";
}
// output people ?
echo $i.". -> ".$p1Name[$i].", ".$p1Beens[$i].", ".$p1Coins[$i].", ".$p1Total[$i];
// 1 bungle 0 4 0
echo "<br>";
echo $i.". -> ".$p2Name[$i].", ".$p2Beens[$i].", ".$p2Coins[$i].", ".$p2Total[$i];
// 1 bert 0 8 3
// 2 fred 0 3 1
echo "<br>";
echo $MainId1, $MainId2;
// 1 2
echo "<br>";
$i++;
}
}else {
echo "No people";
}
}
A better more refined solution would be very helpful.
Some advices after looking on code:
Prepare data before sending it to view
Next try to separate logic from view
My answer shows how array can be separeted in arrays by id:
$people=$results["results"]["people"];
$result=[];
$count=count($people);// i don't need special numbpeople in array
for ($i=0; $i<$count; $i++){
$id=$people[$i]['mainId'];
if (!isset($result[$id]))
$result[$id]=[];//create new array for this id
$result[$id][]=$people[$i]; //add people to this collection
}
After above loop in results we have this structure:
[
1 => [ [peopley],[peoplex] ]
2 => [ [peoplez],[peoplew] ]
....
]
This structure is grouped by mainId.
How to show people from above structure:
$size=count($result)
for ($i=0;$i<$size; $i++){
//loop on groups
$peoples=$result[$i];//array with people in this group
$groupSize=count($peoples);
for ($j=0;$j<$groupSize; $j++){
//loop in group
echo $peoples[$j]["name"];//example show name
}
}
I am working in multidimensional array, i have an array like this and i want to merge array
[0] => Array
(
[QuizId] => 173
[QuizName] => Reprocessing Surgical Drapes and Gowns
[totalexams] => 1
[UserScore] => 8
[MaxScore] => 20
[passed] => 1
[CategoryId] => 1
[CategoryName] => CRCST
[totalTimes] => 1
[orderId] => 19
[productId] => 50
)
[1] => Array
(
[QuizId] => 173
[QuizName] => Reprocessing Surgical Drapes and Gowns
[totalexams] => 1
[UserScore] => 8
[MaxScore] => 20
[passed] => 1
[CategoryId] => 1
[CategoryName] => CRCST
[totalTimes] => 1
[orderId] => 20
[productId] => 50
)
All i need is to make array by join orderId 19,20
ie,
[0] => Array
(
[QuizId] => 173
[QuizName] => Reprocessing Surgical Drapes and Gowns
[totalexams] => 1
[UserScore] => 8
[MaxScore] => 20
[passed] => 1
[CategoryId] => 1
[CategoryName] => CRCST
[totalTimes] => 1
[orderId] => 19,20
[productId] => 50
)
I want to arrange like this.please help me to achieve this
You can try something like this
//This is your old array that you describe in your first code sample
$old_array = array();
// This will be the new joined array
$new = array();
// This will hold the key-pairs for each array within your initial array
$temp = array();
// This will hold all the values of orderId
$orderId = array();
// Loop through each first-level array with the original array
foreach($old_array as $val) {
//Loop through each second-level array
foreach($val as $key => $value) {
// Set the key-pair values in the $temp array
$temp[$key] = $temp[$value];
if($key == "orderId") {
// Add the current orderId value to the orderId array
array_push($orderId,$value);
// Join all the orderId values into the $temp array
$temp[$key] = join(",", $orderId);
}
}
}
//Push the final values to the new array to get a 2 dimensional array
array_push($new, $temp);
Note: I did not test any of the following code so it is very likely to not work at first.
This is also VERY bad array design and there are more likely easier and more practical solutions to this problem, but you will need to give more details on what you want to achieve
$original_array = array(); //this is the array you presented
$new_array = array(); //this is the output array
foreach($original_array as $arr) {
foreach($arr as $key => $value) {
if(array_key_exists($key, $new_array)) { //if you already assigned this key, just concat
$new_array[0][$key] .= "," . $value;
} else { //otherwise assign it to the new array
$new_array[0][$key] = $value;
}
}
}
It will give you the desired result
$arrNew = array();
$i = 0;
foreach($multiDArray as $array)
{
foreach($array as $key=>$value)
{
if($i > 0)
{
if($arrNew[$key] != $value)
{
$str = $arrNew[$key].','.$value;
$arrNew[$key] = $str;
}
}
else
{
$arrNew[$key] = $value;
}
}
$i++;
}
print_r($arrNew);
Result:
Array
(
[QuizId] => 173
[QuizName] => Reprocessing Surgical Drapes and Gowns
[totalexams] => 1
[UserScore] => 8
[MaxScore] => 20
[passed] => 1
[CategoryId] => 1
[CategoryName] => CRCST
[totalTimes] => 1
[orderId] => 19,20
[productId] => 1
)
I have an array of objects.
What I need is to take each [name] of each object in put into another array, but I don't want duplicates.
How can I do it?
Array (
[0] => ADOFetchObj Object
(
[name] => Team 1
[att] => None
[idGrupo] => 1
[idModulo] => 4
[ler] => 1
[escrever] => 1
[excluir] => 1
)
[1] => ADOFetchObj Object
(
[name] => Team 1
[nomeModulo] => Aplicar Juros
[idGrupo] => 1
[idModulo] => 1006
[ler] => 1
[escrever] => 1
[excluir] => 1
)
[2] => ADOFetchObj Object
(
[name] => Team 2
[att] => None
[idGrupo] => 1
[idModulo] => 10
[ler] => 1
[escrever] => 1
[excluir] => 1
)
[3] => ADOFetchObj Object
(
[name] => Team 2
[att] => None
[idGrupo] => 1
[idModulo] => 1012
[ler] => 1
[escrever] => 1
[excluir] => 1
)
)
Thanks!
You can do this:
$names = array();
foreach($arr as $list) {
$names[$list->name] = true; // can be *any* arbitrary value
}
$names = array_keys($names);
This will work because by definition array keys have to be unique.
array_unique(array_map(function($element) {
return $element->name;
}, $my_array));
There you go
$res = array();
foreach($arr as $var)
{
if(!in_array($var->name, $res))
{
$res[] = $var->name;
}
}
First, copy the names to a new array:
$arrNames = array();
foreach($arrOriginal as $objObject) {
array_push(
$arrNames,
$objObject->name
);
}
Then remove the duplicate names:
$arrNames = array_unique($arrNames);
$n = array();
foreach($array as $d) $n[] = $d->name;
$n = array_unique($n);
I have the below array coming though, ideally I am looking for a way of matching one value and printing out another value.
e.g.
if($randomvalue == $cards[Card][unit_id]) { echo $cards[SaleDetail][date_pid_signed]; }
I'm not sure exactly how to go about getting the above to work with the current array structure as below.
Any ideas how I can get around this?
Thanks
$cards = Array
(
[0] => Array
(
[Card] => Array
(
[id] => 210
[property_id] => 4
[unit_id] => 90
)
[SaleDetail] => Array
(
[property_agent] =>
[date_pid_signed] => 2012-06-15
[property_date_listed] =>
)
)
[1] => Array
(
[Card] => Array
(
[id] => 209
[property_id] => 4
[unit_id] => 103
)
[SaleDetail] => Array
(
[property_agent] =>
[date_pid_signed] => 2011-10-21
[property_date_listed] =>
)
)
)
foreach($cards as $card){
if($randomvalue == $card[Card][unit_id]) {
echo $card[SaleDetail][date_pid_signed];
}
}
Use $cards[0]['Card']['unit_id'] and $cards[0]['SaleDetail']['date_pid_signed']. Notice the indexes [0]. You can then use [1].
You might also want to check foreach or for loops!
if($randomvalue == $cards[0][Card][unit_id]) { echo $cards[0][SaleDetail][date_pid_signed]; }
also you can do
foreach($cards as $card)
{
if($randomvalue == $card[Card][unit_id])
{
echo $card[SaleDetail][date_pid_signed];
}
}
I'm using this function to search the (highest) array key when a value of userid is found:
function array_search_value($needle,$haystack) {
foreach($haystack as $key => $value) {
if(in_array($needle, $value)) return $key;
}
}
My array looks like this (it's generated by a simple query):
Array
(
[0] => Array
(
[0] => 1
[userid] => 1
[1] => 2
[score1] => 2
[2] => 0
[score2] => 0
)
[1] => Array
(
[0] => 3
[userid] => 3
[1] => 2
[score1] => 2
[2] => 2
[score2] => 2
)
[2] => Array
(
[0] => 4
[userid] => 4
[1] => 1
[score1] => 1
[2] => 1
[score2] => 1
)
[3] =>
)
This code:
echo array_search_value(4, $r)
Returns 2, which is correct.
Looking for 1 gives 0, which is correct.
However, when I search for 2 (which can't be found), it returns 0.
This, off course, is not correct... What I want it to do is return nothing at all, not 0.
I've tried tweeking the function by adding "== true" but that won't work either.
Anyone know's how to fix this?
Thanks a lot!
when I search for 2 (which can't be found), it returns 0. This, off course, is not correct...
Looking at your provided array, it is correct. The value 2 appears in key 0:
[0] => Array
(
[0] => 1
[userid] => 1
[1] => 2 // here
[score1] => 2 // and here
[2] => 0
[score2] => 0
)
If you only want to look at the userid key, then you can't just use in_array(), but have to do such:
<?php
function array_search_value($needle,$haystack) {
foreach($haystack as $key => $value) {
if($value['userid'] === $needle) return $key;
}
return null; // not found
}
if (array_search_value(2, $r) === null) { /* doesn't happen */ }
When you search for 2 you will get 0 since you have $haystack[0][score1] = 2. You need to specify that you're looking for userid and not anything else.
foreach($haystack as $key => $value) {
if ($value['userid'] == $needle) {
return $key;
}
}