How can i reformat array this array? - php

So i have this database table
From that table i want to achievie this (My Expected result)
I don't know the best way to handle this, so for now i create two query.
My first query
SELECT * FROM ( select convert(created_date,date) created_date,code,'' code2,count(code) total, 0 total2
from morning_briefing
where convert(created_date,date) = convert('" . $selected_date . "',date) and code IS NOT NULL
group by code order by created_date desc) a order by total desc
My second query
SELECT * FROM ( select convert(created_date,date) created_date,''code,code2,0 total,count(code2) total2
from morning_briefing
where convert(created_date,date) = convert('" . $selected_date . "',date)
and code2 IS NOT NULL
group by code2 order by created_date desc) a order by total2 desc
Below is result for my query
Array
(
[0] => stdClass Object
(
[created_date] => 2021-03-16
[code] => AA
[code2] =>
[total] => 2
[total2] => 0
)
[1] => stdClass Object
(
[created_date] => 2021-03-16
[code] => AB
[code2] =>
[total] => 1
[total2] => 0
)
[2] => stdClass Object
(
[created_date] => 2021-03-16
[code] => BB
[code2] =>
[total] => 1
[total2] => 0
)
)
then my second query result is this
Array
(
[0] => stdClass Object
(
[created_date] => 2021-03-16
[code] =>
[code2] => AB
[total] => 0
[total2] => 2
)
[1] => stdClass Object
(
[created_date] => 2021-03-16
[code] =>
[code2] => AA
[total] => 0
[total2] => 1
)
)
So, i want to merge both of the array , then i want to order total column desc, the second order is total2
Btw, i'm using mysql table. So how can i achieve my expected result (above), thanks in advance.

You can loop through your $results1 and $result2 and create a new array that contains data in your expected result format.
$total = max(count($result1), count($result2));
$formatted = [];
for($i = 0; $i < $total; $i++) {
$formatted[] = [
'code' => isset($result1[$i]) ? $result1[$i]->code : '-',
'total' => isset($result1[$i]) ? $result1[$i]->total : 0,
'code2' => isset($result2[$i]) ? $result2[$i]->code2: '-',
'total2' => isset($result2[$i]) ? $result2[$i]->total2 : 0
];
}

Related

How to get the data Using Yii2 Query Builder

What i am trying
I have 2 table staff and salarydetails,i want to fetch staff name and there respective salary
$salaries = SalaryDetails::find()->select('salary_details.total_salary AS salary,staff.name AS name')
->leftJoin("staff",'salary_details.staff_id = staff.id');
if ($fcreated_date != null && $tcreated_date != null) {
$salaries->andFilterWhere(['>=','salary_details.salary_given_date', $fcreated_date]);
$salaries->andFilterWhere(['<=', 'salary_details.salary_given_date', $tcreated_date]);
}
when i try to print sql raw query by using
echo $salaries->createCommand()->getRawsql();
i got SELECT salary_details.total_salary AS salary, staff.name AS name FROM salary_details LEFT JOIN staff ON salary_details.staff_id = staff.id
and this query gives the data i wanted in phpMyadmin
But the array gives ie, print_r($salaries); gives
yii\db\ActiveQuery Object ( [sql] => [on] => [joinWith] => [select] => Array ( [0] => salary_details.total_salary AS salary [1] => staff.name AS name ) [selectOption] => [distinct] => [from] => [groupBy] => [join] => Array ( [0] => Array ( [0] => LEFT JOIN [1] => staff [2] => salary_details.staff_id = staff.id ) ) [having] => [union] => [params] => Array ( ) [_events:yii\base\Component:private] => Array ( ) [_behaviors:yii\base\Component:private] => Array ( ) [where] => [limit] => [offset] => [orderBy] => [indexBy] => [modelClass] => common\models\SalaryDetails [with] => [asArray] => [multiple] => [primaryModel] => [link] => [via] => [inverseOf] => )
Thanks,
As you can see in your print_r, $salaries is an ActiveQuery instance. Call the methods ->asArray()->all() on it to get the records.
$query = SalaryDetails::find()
->select('salary_details.total_salary AS salary,staff.name AS name')
->leftJoin("staff",'salary_details.staff_id = staff.id');
if ($fcreated_date != null && $tcreated_date != null) {
$query->andFilterWhere(['>=','salary_details.salary_given_date', $fcreated_date]);
$query->andFilterWhere(['<=', 'salary_details.salary_given_date', $tcreated_date]);
}
$salaries = $query->asArray()->all();
Note that without asArray the all would return an array of SalaryDetails records and you would loss the staff name.

Sum Max values of a group By

I have this query, that produces next result
$result = DB::table('contagenshora')
->select(DB::raw('post_id as post_id'), DB::raw('product_id'), DB::raw('max(val) as maxHour'), DB::raw('hour'))
->whereBetween('date', array($dt->toDateTimeString(), $dt2->toDateTimeString()))
->where('hour', '=', $actHour->hour)
->groupBy(DB::raw('post_id'), DB::raw('product_id'))
->get();
Result: Array ( [0] => stdClass Object ( [post_id] => 1 [product_id] => 1 [maxHour] => 4 ) [1] => stdClass Object ( [post_id] => 1 [product_id] => 2 [maxHour] => 3 ) [2] => stdClass Object ( [post_id] => 4 [product_id] => 0 [maxHour] => 6 ) ) )
Now, I need the sum of "maxHour", but grouped by "post_id", I need something like this:
(For example, for post_id = 1, I need the sum of 4+3)
Result: Array ( [0] => stdClass Object ( [post_id] => 1 [maxHour] => 7 ) [1] => stdClass Object ( [post_id] => 4 [maxHour] => 6 ) ) )
How can I do this?
Just remove the product_id from group by clause and select then. Also no need to use DB::raw() for direct selectable columns.
$result = DB::table('contagenshora')
->select('post_id', DB::raw('max(val) as maxHour'))
->whereBetween('date', array($dt->toDateTimeString(), $dt2->toDateTimeString()))
->where('hour', $actHour->hour)
->groupBy('post_id')
->get();

connect arrays into one

How i can transform this first array [ONE}: Into second array [TWO} where i can call meta_key and than i get var: i get this array by calling specified sql rows and i am using this query: $user_data = $wpdb->get_results("SELECT * FROM $wpdb->usermeta WHERE user_id = $fivesdraft->user_id "); maybe its another better way to connect it in query? not in PHP
Array ONE
(
[0] => stdClass Object
(
[umeta_id] => 16
[user_id] => 2
[meta_key] => nickname
[meta_value] => user1
)
[1] => stdClass Object
(
[umeta_id] => 17
[user_id] => 2
[meta_key] => first_name
[meta_value] => testname
)
[2] => stdClass Object
(
[umeta_id] => 18
[user_id] => 2
[meta_key] => last_name
[meta_value] => testlastname
)
[3] => stdClass Object
(
[umeta_id] => 19
[user_id] => 2
[meta_key] => description
[meta_value] => user desc
)
)
Array TWO
(
[nickname] => 'user1'
[first_name] => 'user desc'
[last_name] => 'user desc'
[description] => 'user desc'
...
)
You can use array_reduce:
$myArray = array_reduce($arrayOne, function ($result, $item) {
$result[$item->meta_key] = $item->meta_value;
return $result;
}, array());
Just loop over the array and write the values in a new array
$two = array();
foreach ($one as $item) {
$two[$item->meta_key] = $item->meta_value;
}

Add key and variable to multidimensional Array based on conditions

I wonder if it's possible to add a key and value to an array, based on certain conditions.
This piece of script makes an api-call to retrieve sportresults from multiple teams based on a teamID number.
$length = $numberofTeams
for ($i = 0; $i < $length; $i++) {
$teamID = $objTeamID[$i]['Teamid'];
$teamResults = 'http://api.com/teamresults/' . $Teamid;
$dataResults = file_get_contents($teamResults);
$objResults[] = json_decode($dataResults, true);
}
The result is an array with this structure:
Array (
[0] => Array (
[errorcode] => 9995
[message] => No results
)
[1] => Array (
[errorcode] => 1000
[message] => Ok, Schedule follows
[List] => Array (
[0] => Array (
[MatchID] => 7683403
[Number] => 630
[Result] => 2 - 1
[Datum] => 2013-08-27
[Tijd] => 2000
[CompType] => B )
[1] => Array (
[MatchID] => 7683403
[Number] => 630
[Result] => 4 - 0 [Datum] => 2013-08-27
[Tijd] => 2000
[CompType] => B )
)
)
[2] => Array (
[errorcode] => 9995
[message] => No results )
)
Before saving it in an MySql database, for later use I need to add the teamID-variable to every result so it would become:
Array (
[0] => Array (
[errorcode] => 9995
[message] => No results
)
[1] => Array (
[errorcode] => 1000
[message] => Ok, Schedule follows
[List] => Array (
[0] => Array (
[teamID] => 'value from $teamID'
[MatchID] => 7683403
[Number] => 630
[Result] => 2 - 1
[Datum] => 2013-08-27
[Tijd] => 2000
[CompType] => B )
[1] => Array (
[teamID] => 'value from $teamID' [MatchID] => 7683403
[Number] => 630
[Result] => 4 - 0
[Datum] => 2013-08-27
[Tijd] => 2000
[CompType] => B )
)
)
[2] => Array (
[errorcode] => 9995
[message] => No results )
)
The length of the array varies and also the number of results vary. I have no influence on the result of the api-call itself, because it's been set up by big sport association.
I'm absolutely no programmer, so I'm out of my depth her, but this is a voluntary job for an amateur sportsclub so hiring a programmer is no option.
Rgds, Bonzyx
if(isset($objResults[1]['List'])){
foreach($objResults[1]['List'] as &$listItem){
$listItem['teamID'] = $teamID;
}
unset($listItem); //good practice to unset this reference to last array element
}
You could do the same with php's array_walk() function, but since you said you're not a programmer I think the foreach method is more clear to you.

Echo return values from rows from db

Does it make difference to get the value of result set when using alias names and join in the SQL generated using zend framwork.
Regarding to the sql resulted from the selected answer in this question I want to print all result in .phtml file.
I make like this
<?php
foreach($this->rows as $row){
echo $row->visit_id . ' ' . $row->rep_id . ' '.$row->target;
?>
When I print the size of $this->rows it returns the correct number of rows, but it doesn't print any thing?!
Edit
here's what I get when I print $rows
Zend_Db_Statement_Pdo Object ( [_fetchMode:protected] => 2 [_stmt:protected] => PDOStatement Object ( [queryString] => SELECT `r`.`rep_id`, `r`.`visit_id`, `v`.`target`, `v`.`visit_id` FROM `visit_report_tb` AS `r` INNER JOIN `inspection_visits_tb` AS `v` ON v.visit_id=r.visit_id WHERE (r.visit_id = 1) ) [_adapter:protected] => Zend_Db_Adapter_Pdo_Mysql Object ( [_pdoType:protected] => mysql [_numericDataTypes:protected] => Array ( [0] => 0 [1] => 1 [2] => 2 [INT] => 0 [INTEGER] => 0 [MEDIUMINT] => 0 [SMALLINT] => 0 [TINYINT] => 0 [BIGINT] => 1 [SERIAL] => 1 [DEC] => 2 [DECIMAL] => 2 [DOUBLE] => 2 [DOUBLE PRECISION] => 2 [FIXED] => 2 [FLOAT] => 2 ) [_defaultStmtClass:protected] => Zend_Db_Statement_Pdo [_config:protected] => Array ( [dbname] => inspection [username] => root [password] => 123456 [charset] => [persistent] => [options] => Array ( [caseFolding] => 0 [autoQuoteIdentifiers] => 1 [fetchMode] => 2 ) [driver_options] => Array ( ) ) [_fetchMode:protected] => 2 [_profiler:protected] => Zend_Db_Profiler Object ( [_queryProfiles:protected] => Array ( ) [_enabled:protected] => [_filterElapsedSecs:protected] => [_filterTypes:protected] => ) [_defaultProfilerClass:protected] => Zend_Db_Profiler [_connection:protected] => PDO Object ( ) [_caseFolding:protected] => 0 [_autoQuoteIdentifiers:protected] => 1 [_allowSerialization:protected] => 1 [_autoReconnectOnUnserialize:protected] => ) [_attribute:protected] => Array ( ) [_bindColumn:protected] => Array ( ) [_bindParam:protected] => Array ( ) [_sqlSplit:protected] => Array ( [0] => SELECT `r`.`rep_id`, `r`.`visit_id`, `v`.`target`, `v`.`visit_id` FROM `visit_report_tb` AS `r` INNER JOIN `inspection_visits_tb` AS `v` ON v.visit_id=r.visit_id WHERE (r.visit_id = 1) ) [_sqlParam:protected] => Array ( [0] => SELECT `r`.`rep_id`, `r`.`visit_id`, `v`.`target`, `v`.`visit_id` FROM `visit_report_tb` AS `r` INNER JOIN `inspection_visits_tb` AS `v` ON v.visit_id=r.visit_id WHERE (r.visit_id = 1) ) [_queryId:protected] => )
If you are using the query you accepted in the other question, your field names should be as you expect.
I usually just var_dump $row to see what's there is what I expect:
<?php
foreach($this->rows as $row){
//Zend_Debug::dump() provides formatted debug info, the second argument is a label
Zend_Debug::dump($row, 'Row')
?>
This should give you a pretty good idea of what each row contains with out all the baggage that $rows has.
Heh, and that's why I pointed You to ReferenceMap i Zend_Db_Tables. Check my answer to Your previous question.
https://stackoverflow.com/a/9905206/1278879
Using my code from Your previous question You could've done it like this:
foreach ($reportRowset as $reportRow) {
echo $reportRow->visit_id . ' ' . $reportRow->rep_id . ' '.$visitRow->target;
}
And that's piece of cake
The row is not an object, its an array and it can be get like this:
print $row['rep_id']

Categories