Convert multidimensional array into single dimensional using values from child arrays - php

I have the following PHP/MYSQL query:
$sql = SELECT type, count(*) AS total FROM stats GROUP BY type
$this->sql = $sql;
function numObjects() {
$stats = $this->conn->query($this->sql);
while($stat_type = $stats->fetch_assoc()){
$category[] = $stat_type;
}
return $category;
}
It's a simple query, but I just can't figure out how to retrieve the data the way I want since it is returning a multidimensional array.
array(2) {
[0]=> array(2) {
["type"]=> string(4) "page"
["total"]=> string(1) "1"
}
[1]=> array(2) {
["type"]=> string(8) "category"
["total"]=> string(1) "1"
}
}
What I'm looking to do is convert the values from each array, into key => value pairs. Like this:
["page"]=> "1"
["category"]=> "1"
I've been able to convert it into a single dimensional array, but not in the correct format.

try this:
$new_array = array();
foreach ($old_array as $elem) {
$new_array[$elem["type"]] = $elem["total"];
}
var_dump($new_array); //for print the array

For PHP >= 5.5, I give you the array_column() function
$reformatted = array_column(
$category,
'total',
'type'
);

Related

How to remove records in php array where there are same values in one column [duplicate]

This question already has answers here:
Filter/Remove rows where column value is found more than once in a multidimensional array
(4 answers)
Closed 9 months ago.
I've a array of associative array
array(xxx) {
[0]=>
array(3) {
["group_id"]=>2
["contact"]=> "foo"
["contact_email"]=> "foo#gmail.com"
}
[1]=>
array(3) {
["group_id"]=>2
["contact"]=> "bar"
["contact_email"]=> "bar#gmail.com"
}
[2]=>
array(3) {
["group_id"]=>2
["contact"]=> "foobar"
["contact_email"]=> "bar#gmail.com"
}
[3]=>
array(3) {
["group_id"]=>2
["contact"]=> "bar"
["contact_email"]=> "bar#gmail.com"
}
to remove duplicate arrays I do this
array_unique( $array, SORT_REGULAR );
But now I would like to do something more specific by eliminating only the arrays that have duplicated key value (contact_email) to obtain this result
array(xxx) {
[0]=>
array(3) {
["group_id"]=>2
["contact"]=> "foo"
["contact_email"]=> "foo#gmail.com"
}
[1]=>
array(3) {
["group_id"]=>2
["contact"]=> "bar"
["contact_email"]=> "bar#gmail.com"
}
How could i do that?
Thank you
Extract to an array and index by contact_email. Since there cannot be duplicate indexes you'll get the last occurrence:
$array = array_column($array, null, 'contact_email');
If you want to re-index that back to integers:
$array = array_values(array_column($array, null, 'contact_email'));
You can use foreach and group them by contact_email
$r = [];
foreach($a as $v){
$r[$v['contact_email']] = $v;
}
print_r(array_values($r));// reorder index
Working example : https://3v4l.org/0oN8h
I think this can help
$arr = [['contact_email' => 'a#a.com'], ['contact_email' => 'a#a.com'], ['contact_email' => 'b#a.com']];
$result = [];
array_map(function ($item) use (&$result) {
$result[$item['contact_email']] = $item;
}, $arr);
print_r($result);

How to merge array two level become one level in php [duplicate]

This question already has answers here:
Is there a function to extract a 'column' from an array in PHP?
(15 answers)
Closed 7 months ago.
halo everyone. now I'm trying to merge array inside array after query from SQL.. and the result like this
array(3) {
[0]=>
array(1) {
["building_id"]=>
string(1) "1"
}
[1]=>
array(1) {
["building_id"]=>
string(1) "2"
}
[2]=>
array(1) {
["building_id"]=>
string(1) "3"
}
}
I already tried to use this code
$result=[];
foreach($bulding_ids as $arr)
{
$result = array_merge($arr['building_id'],$result);
}
but maybe that is not a answer
I want to that array become like this
array(3) {
[0]=>
int(1)
[1]=>
int(2)
[2]=>
int(3)
}
Can I make like that?
You could just use array_column().
$result = array_column($building_ids, 'building_id');
array_column() returns the values from a single column of the input,
identified by the column_key. Optionally, an index_key may be
provided to index the values in the returned array by the values from
the index_key column of the input array.
This eliminates the need for a loop.
Output:
array(3) { [0]=> string(1) "1" [1]=> string(1) "2" [2]=> string(1) "3" }
The only downside of this, is that all of the building ID's will be stored as strings. If this is a problem for your application, you can easily use array_map() to convert them to ints.
Directly after the line above, do this:
$result = array_map('intval', $result);
array_map() returns an array containing all the elements of array1
after applying the callback function to each one. The number of
parameters that the callback function accepts should match the number
of arrays passed to the array_map()
Output:
array(3) { [0]=> int(1) [1]=> int(2) [2]=> int(3) }
You can also make this a single line solution:
$result = array_map('intval', array_column($building_ids, 'building_id'));
But in my opinion this looks a bit more messy.
You need to parse every element in your first array and return the id. Then you convert it into int type. Finally, you save the new value into a new array.
<?php
$bulding_ids[] = ["Building_id" => "1"];
$bulding_ids[] = ["Building_id" => "2"];
$bulding_ids[] = ["Building_id" => "3"];
$result = array();
foreach($bulding_ids as $val){
$result[] = (int)$val['Building_id'];
}
var_dump($result);

how to compare multiple arrays for higher value based on one specific key?

I have multiple arrays. I want to compare these arrays key values with one another and output only one array which has the higher value than others. Here is my array
array(4) { ["type"]=> string(6) "Person" ["relevance"]=> string(8) "0.645481" ["count"]=> string(1) "1" ["text"]=> string(15) "RAJESH NELATURI" }
array(4) { ["type"]=> string(6) "Person" ["relevance"]=> string(8) "0.567918" ["count"]=> string(1) "2" ["text"]=> string(11) "Layoutlands" }
array(4) { ["type"]=> string(6) "Person" ["relevance"]=> string(8) "0.546824" ["count"]=> string(1) "1" ["text"]=> string(9) "N. Rajesh" }
I want to compare the key "relevance" and filter the array which has higher relevance value. In this case The first array which has the value "0.645481" and print the arrays key[text]. Here it should print RAJESH NELATURI
Here is a solution :
$higher = array('relevance' => 0);
foreach($myArray as $key) {
if($key['relevance'] > $higher['relevance']){
$higher = $key;
}
}
At the end, $higher will have the biggest relevance and is equal to :
$higher = array(4) { ["type"]=> string(6) "Person" ["relevance"]=> string(8) "0.645481" ["count"]=> string(1) "1" ["text"]=> string(15) "RAJESH NELATURI" }
now you can print the higher text :
echo $higher['text'];
UPDATE:
But it seems all 'relevance' values in your array are string, So they can not be compared with each other! you have to change them to float,
Try to produce this array in another way to have float values,
If you can't, Try this code instead :
$higher = array('relevance' => 0);
foreach($myArray as $key) {
if((float)$key['relevance'] > (float)$higher['relevance']){
$higher = $key;
}
}
this code changes string to float before compare.
find the relevance with max value, and the index. Here is the code, hope it helps.
$relevances = array_column($array, 'relevance');
$values = array_values($relevances);
$map = array_combine($values, array_keys($$relevances));
echo $array[$map[max($values)]]['text'];
Iterate through the arrays in a replace-if-higher basis.
$currentMax = PHP_INT_MIN; // it is impossible for any entries to be smaller than this value
foreach($arrays as $array){
$keyValue = $array["relevance"]; // not exactly sure what you mean by "key value"
if($keyValue > $currentMax){
$currentMax = $keyValue;
$currentName = $array["text"]'
}
}
$currentName should be set as lonig as $arrays is not empty and the $keyValue of any entries is greater than PHP_INT_MIN.

sorting by smallest value in array inside of array in php

I have an array of menus (breakfast, lunch, dinner) with their start times (08:00:00, 11:00:00, 16:00:00), and I need to pull out the menu closest to now() in the future and know which menu it is. This is what I have:
$menus = array(
array("breakfast", "08:00:00"),
array("lunch", "11:00:00"),
array("dinner", "16:00:00")
);
This is how I've been getting the soonest menu (assuming it's before 8am).
foreach($menus as $a) {
$menu[] = $a[0];
$time[] = $a[1];
}
echo min($time);
This gets me the soonest time 08:00:00, but I can't figure out how to attach the menu to this realization. Let's say it echoes 08:00:00, how can I get the $menu in there so I can also know that 08:00:00 corresponds to "breakfast"?
why not
$menus = array(
'08:00:00' => 'breakfast'
...
'16:00:00' => 'dinner'
)
Times are the key, values are the menu attached to that time.
If you inside on using the two-array structure, then as long as your keys in both arrays have 1:1 correspondence in positions, you can find the key for that value, then look up in the other array:
$min = min($time);
$key = array_keys($time, $min);
$menu = $menu[$key];
To sort the array by the lowest value, preserving the rest the keys, you can try the following:
uasort($menus, function($a, $b) {
return $a[1] - $b[1];
});
For example, if you run the above for the following array
$menus = array(
array("dinner", "16:00:00"),
array("breakfast", "08:00:00"),
array("lunch", "11:00:00"),
array("brunch", "09:30:00")
);
you will get the following result:
array(4) {
[1]=>
array(2) {
[0]=>
string(9) "breakfast"
[1]=>
string(8) "08:00:00"
}
[3]=>
array(2) {
[0]=>
string(6) "brunch"
[1]=>
string(8) "09:30:00"
}
[2]=>
array(2) {
[0]=>
string(5) "lunch"
[1]=>
string(8) "11:00:00"
}
[0]=>
array(2) {
[0]=>
string(6) "dinner"
[1]=>
string(8) "16:00:00"
}
}
While I that the array structure can be made better, I was just curious to check how to do it with your specific data-set, so here goes:
$menus = array(
array("breakfast","08:00:00"),
array("lunch","11:00:00"),
array("dinner","16:00:00")
);
foreach($menus as $a) {
$menu[] = $a[0];
$time[] = $a[1];
}
Considering this is how far you have reached so far, you can complete it by having a simple iterative function:
function getMenu($time,$menus)
{
foreach($menus as $menu)
{
if($menu[1] == $time) return($menu[0]);
}
}
And you can call it so: echo getMenu(min($time),$menus);
Not optimal, and the data structure leaves much to be desired, but will get the job done...

Saparate array data with comma

I have an function that return an array
[0]=>
array(2) {
[0]=>
string(2) "22"
[1]=>
string(9) "Plantroom"
}
[1]=>
array(2) {
[0]=>
string(2) "22"
[1]=>
string(4) "dfdf"
}
}
sometime my array have one object or multiple .
[0]=>
array(2) {
[0]=>
string(2) "23"
[1]=>
string(4) "sec"
}
}
now I want to show my array data by comma separated.
like
for first array => Plantroom,dfdf
for second array =>sec
I am using this code but not work
my function
function area_name($game_id)
{
include_once('Model/Game.php');
$c2 = new Game();
$cd2 = $c2->Select_area($game_id);
return $cd2;
}
and call my function as
implode(", ", area_name($cd[$i][0]))
But my output show text Array
Because area_name() is not just returning an array, its returning an array of arrays. implode() will join the elements of the array that area_name() returns assuming they are strings, but those elements are also arrays and as such they are stringified to text "Array".
To obtain the desired output from implode() you would have to first generate an array with only the values you want from the structure returned by area_name().
For instance:
$data = array_map(function ($a) { return $a[1]; }, area_name($cd[$i][0]));
echo implode(', ', $data);

Categories