MySQL to PHP Array - php

Can you please help me extracting MySQL data in php array.
my sql:
SELECT count(*) as total, post_type as type FROM wp_posts group by post_type;
to php, like below:
<?php $total = array(5,7, .. , ..); $type = array('Page', 'Post', '..',..'); ?>
Array should come from database
Thanks :)

You can't get two separate arrays from single SQL query either you have to run the mysql query two times or Write a PHP code which gives you the desired result.
Your current query will give result as follow.
Array
(
[0] => Array
(
[total] => 5
[post_type] => Page
)
)
Now you have to traverse these array to create two separate arrays you want.
$total=array_column($result,'total');
$type = array_column($result,'post_type');
Above code will give you two separate arrays.
Thanks to Niet the Dark Absol for array_column, it looks more clean then traversing manually.

Related

PHP- Sort Indexed array according to the values of another array

Basically,I want to sort an array based on another array.
As in,
<?php
$movies=array("Avengers","Spiderman","Batman","Flash");
$ratings=array(9,3,4,7,);
?>
In other words,the $movies[0]("Avengers") has a ratings of 9 , $movies[1]("Spiderman") has a rating of 3 and so on.
I want the ratings array to be sorted numerically in descending order and thus sorting the movies array.I will like this to be in a function.
Thus, the array will be thus:
<?php
$movies=array("Spiderman","Batman","Flash","Avengers",);
$ratings=array(3,4,7,9);
?>
The ratings array has been sorted and thus the movies array has also been sorted but according to the ratings array.
I am sorry I am a newbie in php and I know that doing that is probably very simple but I don't know how to do It.The only way I can think of is using inserting into an sql table then selecting from it in descending order but that will probably be a very bad idea.....
Any help is highly appreciated. Thanks in advance.
Oh and if it is easier to do it in Laravel (I use laravel) please show me how
You can use array_combine() to combine movie names and ratings.
So, that movie names will be the keys of resulting array and ratings will be the values.
Now, sort using arsort() so that the new array will be sorted in descending order by ratings keeping movie names as it is.
Print the array.
Code:
<?php
$movies=array("Spiderman","Batman","Flash","Avengers",);
$ratings=array(3,4,7,9);
$movieRatings = array_combine($movies, $ratings);
arsort($movieRatings);
echo '<pre>';print_r($movieRatings);
?>
Output:
Array
(
[Avengers] => 9
[Flash] => 7
[Batman] => 4
[Spiderman] => 3
)
try this,
array_combine ( array $keys , array $values ) : array
it works by setting the values in one array as keys of another array which in your case is your movies.
<?php
$movies=array("Avengers","Spiderman","Batman","Flash");
$ratings=array(9,3,4,7,);
$result = array_combine ( $movies, $ratings);
// then sort this way...
arsort($result, 0);
?>
documentation for both functions are here...
https://www.php.net/manual/en/function.array-combine.php
https://www.w3schools.com/php/func_array_arsort.asp

How to get array value join related array value?

I am newly php developer, i have worked on codeigniter project, get data from database below
Array(
[0]=>(
[id]=>1,
[no_of_services]=>guide,assistant
),
[services]=>(
[id]=>1,,
[quote_id]=>1,
[tour_reference]=>GD/Amsterdam/2019
))
But i need to required below this:
Array(
[0]=>(
[id]=>1,
[no_of_services]=>guide,assistant,
[services]=>(
[id]=>1,,
[quote_id]=>1,
[tour_reference]=>GD/Amsterdam/2019
)
),
)
Please help me how to array of inner array function
Thanks Regards
It seems that you are not processing the data retrieved from database, correctly.
We could help you more, only if you provide your code snippet here.
However you can transform your array by using following steps:
1) Initialize a new empty array named $output
2) Iterate your database result array in a 'for' loop
3) In 'for' loop, do operations to insert in $output array as per your desired format.
4) In the end, $output array is your desired array.

Break Up Array and output to table?

I run a gaming server and it keeps some information in a database.
I run a MySQL query that pulls information like cargo_items (below).
How can I format this data properly in PHP? I'd like for it to be in a table. Is that possible? My knowledge of handing arrays like this is limited do to the complex nature. This is how the data is returned from the database.
Array
(
[0] => Array
(
[0] => Array
(
[id] => 2237
[cargo_weapons] =>
[
["MMG_02_black_F","","","",[],""],
["arifle_SDAR_F","","","",[],""],
["arifle_SDAR_F","","","",[],""],
["arifle_SPAR_03_khk_F","","","",[],""],
["LMG_Zafir _F","","","",[],""],
["MMG_02_black_F","","","",[],""],
["MMG_02_black_F","","","",[],""]
]
)
)
)
The output should be a table:
Weapons
-------
MMG_02_black_F
arifle_SDAR_F
arifle_SDAR_F
arifle_SPAR_03_khk_F
LMG_Zafir_F
MMG_02_black_F
MMG_02_black_F
Since you have multidimensional array, you need custom recursion function, or, in your specific case, you could use something like this:
function get_items($item, $key)
{
if(!empty($item) && $key=='cargo_weapons')
//your html table cells
echo "$item<br>";
}
array_walk_recursive($array, 'get_items');
array_walk_recursive
will do the job (this function returns true or false), but you can (ab)use it to display desired HTML too.

Associative array from a database with codeigniter

On my models I try to write a php model that will get me a associative array from a database. But I don't quite know how to approach this.
So after I execute this SQL query:
SELECT balance_events.weight,balance_events.added_date,
balance_entries.mid FROM balance_events, balance_entries
WHERE balance_entries.added_date BETWEEN '2016-08-02' AND '2016-08-03'
AND balance_entries.ptid =12
AND balance_entries.beid = balance_events.id
I will get this table:
And from that table I want to extract a asociative array that it will look like this:
count = ['13'=>1, '6'=>4, '16'=>3, '4'=>3]
where 'mid'=>number of how many times that mid can be found in the table.
ex. mid '13'=>1 cause you can found it only once.
I think that I will have to use SQL COUNT function, but how I can aggregate all of this in a PHP model in codeigniter? I know how to configure controller and view, but I don't know how to actually do the actual php model that will get me the desired array.
Try this query may help you ,
$result = $this->db->select('balance_events.weight,balance_events.added_date,COUNT(balance_entries.mid) as mid_count')
->from('balance_events, balance_entries')
->where('balance_entries.added_date BETWEEN "2016-08-02" AND "2016-08-03" ')
->where('balance_entries.ptid','12')
->where('balance_entries.beid','balance_events.id')
->group_by('balance_entries.mid')
->get();
return $result->result_array();
I'm not sure how you would create this in SQL but since you tagged php, I wrote a function that would do just this.
<?php
$query = array(array("mid"=>13), array("mid"=>2), array("mid"=>13), array("mid" =>6), array("mid" => 13), array("mid" => 6));
function createMidArray($queryResult){
$returnArray = array();
foreach ($queryResult as $qr){
$returnArray[$qr['mid']]++;
}
return $returnArray;
}
print_r(createMidArray($query));
?>
The output of this was Array ( [13] => 3 [2] => 1 [6] => 2 ) which matches up to my inputted $query (which is a 2D array). I'm expecting the output of your query is stored in a similar array, but with more data and keys

Calculate avrage of mysql result php

I want to calculate the avrage of a mysql result in PHP (I'm using CodeIgniter as framework).
My (model) code:
$query = $this->db->query('SELECT stars FROM feedback');
$res = $query->result_array();
$avrage = array_sum($res); // The impossible part
$avrage = round($avrage,0);
The result of the query looks like this: (print_r) Array ( [0] => Array ( [stars] => 5 ) [1] => Array ( [stars] => 3 ) )
I just want the '5' and '3' in a separate array, so array_sum() can do it's job. How do I do this?
Thanks.
You can do it in SQL directly using AVG()
SELECT avg(stars) as avg_stars
FROM feedback
Why not use AVG directly in your query?
'SELECT AVG(stars) as average FROM feedback'
The best way to do this would be to modify your SQL query, like this: SELECT AVG(stars) as stars_average FROM feedback. Then, after fetching the result set, you can do the following in your PHP code: $average = $res[0]['stars_average'];.

Categories