logo
down
shadow

Grouped Array data


Grouped Array data

By : President
Date : October 22 2020, 08:10 AM
This might help you I'm trying to figure out how to get data from the following data structure. I managed to group a flat array into the following array, but am finding it difficult to find the proper resources to explain how to get the data out. I'm looking to get the count of the items in each group. Then i'd like to print the ids from the inner array...
code :
$my_array1 = array(
    'grinds' =>
        array(
            0 =>
                array(
                    'id' => 16562,
                    'slug' => 'grinds',
                ),
            1 =>
                array(
                    'id' => 16561,
                    'slug' => 'grinds',
                ),
        ),
    'online-grinds' =>
        array(
            0 =>
                array(
                    'id' => 16566,
                    'slug' => 'online-grinds',
                ),
        ),
);
$counts = array();
foreach ($my_array1 as $key => $val) {
    $counts[$key] = count($val);
}
var_dump($counts);
array(2) {
    ["grinds"]=>
    int(2)
    ["online-grinds"]=>
    int(1)
}
$innerids = array();
foreach ($my_array1 as $key => $val) {
    foreach ($val as $key2 => $val2) {
        $innerids[] = $val2['id'];
    }
}
var_dump($innerids);
array(3) {
    [0]=>
    int(16562)
    [1]=>
    int(16561)
    [2]=>
    int(16566)
}


Share : facebook icon twitter icon
PHP ARRAY display grouped data from the array based on date ranges

PHP ARRAY display grouped data from the array based on date ranges


By : Brandon Whosville
Date : March 29 2020, 07:55 AM
With these it helps To get all results for a specific date range, don't group by date; instead use a WHERE clause to limit the date of the count. Otherwise the query is very similar.
code :
$query = mysql_query("SELECT type, count(*) FROM tracking WHERE htcode = '$htG' AND type IN ('viewed', 'shared', 'printed', 'emailed', 'used') AND date >= '$start_date' AND date <= '$end_date' GROUP BY type");
SELECT type, count(*)
FROM tracking
WHERE htcode = '$htG'
  AND type IN ('viewed', 'shared', 'printed', 'emailed', 'used')
  AND date >= '$start_date' AND date <= '$end_date'
GROUP BY type
$start_date = date('Y-m-d');
$end_date = date('Y-m-d');
$start_date = date('Y-m-d', strtotime('yesterday'));
$end_date = date('Y-m-d', strtotime('yesterday'));
$start_date = date('Y-m-d', strtotime('30 days ago'));
$end_date = date('Y-m-d');
function report_range($htG, $start_date, $end_date) {
    $query = mysql_query("SELECT type, count(*) FROM tracking WHERE htcode = '$htG' AND type IN ('viewed', 'shared', 'printed', 'emailed', 'used') AND date >= '$start_date' AND date <= '$end_date' GROUP BY type");

    while ($result = mysql_fetch_assoc($query)){
        echo $start_date . '-' . $end_date . ' / ' . $result['type'] . ' = '  . $result['count(*)'];
        echo '<br>';
    }
}
report_range($htG, date('Y-m-d', strtotime('30 days ago')), date('Y-m-d'));
How to add error bars to a Data Frame Grouped bar plot or even an array of arrays grouped bar plot?

How to add error bars to a Data Frame Grouped bar plot or even an array of arrays grouped bar plot?


By : ice
Date : March 29 2020, 07:55 AM
it should still fix some issue In case someone else ever searches for this particular issue, I wanted to post the solution that finally worked. Apparently, in earlier versions of Pandas (0.013.1 was what I was previously using) there was an issue with trying to to what I was attempting to do with the second data frame. In 0.15, it seems to work now! So, for completeness, here's the code that I was able to use to plot grouped bar plots with associated errors for each individual measurement value:
code :
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
from pylab import *

opacity = 0.6

Measured = (1010, 1119, 1124, 1852, 1862, 876, 889, 891, 873, 873, 872, 1900, 1890, 1901)

C = (80,70,70,70,70,70)

myarray = [[1009, 1010],
 [1122, 1119, 1124],
 [1842, 1852, 1862],
 [881, 876, 889, 891],
 [880, 873, 873, 872],
 [1890, 1900, 1890, 1901]]

e1 = [[4.3, 16.4],
 [4.6, 16.8, 16.2],
 [11.4, 14.3, 14.2],
 [3.7, 11.4, 11.6, 11.6],
 [3.9, 16.7, 17.2, 16.6],
 [8.3, 13.4, 13.9, 13.6]]

length = len(sorted(myarray,key=len, reverse=True)[0])
s=np.array([myarrayi+[None]*(length-len(myarrayi)) for myarrayi in myarray])

length2 = len(sorted(e1,key=len, reverse=True)[0])
e2=np.array([e1i+[None]*(length2-len(e1i)) for e1i in e1])

df = pd.DataFrame(s, columns=['Theo', 'Exp1', 'Exp2', 'Exp3']) #DataFrame of the Theoritical and experimental values
df2 = pd.DataFrame(e1, columns=['Theo', 'Exp1', 'Exp2', 'Exp3']) #DataFrame of the error that I wan to add as error bars to the first data frame
df[['Theo', 'Exp1', 'Exp2', 'Exp3']].plot(kind='bar', yerr=df2[['Theo', 'Exp1', 'Exp2', 'Exp3']].values.T, color=['r', 'b', 'b', 'b'], alpha = opacity,error_kw=dict(ecolor='k'))


plt.xlim([-.5, len(C)-.5]) 
plt.ylim([min(Measured)-500, max(Measured)+200]) # Uses the min and max values of the matrix elements to set the axis boundaries so the scaling is the same all of the time
xlabel("Theoretical vs Experimental Values")
ylabel("Arbitrary units")
title('Comparison Data Grouped Plots', color='#000000', fontsize=18)
plt.tight_layout()
plt.show()
PHP grouped up data by their dates and put them in an array

PHP grouped up data by their dates and put them in an array


By : user1733616
Date : March 29 2020, 07:55 AM
this one helps. I have this data from my database, this is for this student , Here you go (untested):
code :
foreach ($items as $item) {
      //just because I can (use array key for ease of accessing it)
      $key = preg_replace('/-\d{2}$/', '', $item['date']);
      //you can use this instead if you want.
      //$key = date('Y-m', strtotime($item->date));

       //we can join our ifs tougher as the deal with the same elements
       //and this will make the code more efficient
      if(!isset($chart[$key])){
         //add $key as month
         $chart[$key] = array('penalty'=>0, 'warning'=>0, 'month'=>$key);         
      }else if ($item->amount > 0) {
         $chart[$key]['penalty'] += $item->count;
      } else {
         $chart[$key]['warning'] += $item->count;
      }

}

 //may want to put the proper content type
 //this tells the ajax call what it is and will parse it 
 //automatically in most browsers, so you can toss that JSON.parse().
 //CAUTION:do not output data before a header call
 //header('Content-type: application/json'); 

 //array_values removes the date key, its easier to built array with it.
 //then we just output the json
 echo json_encode(array_values($chart));
Rename keys in grouped array to represent the date they are grouped by

Rename keys in grouped array to represent the date they are grouped by


By : user3641561
Date : March 29 2020, 07:55 AM
Any of those help I have an array that I have grouped by 1 minute, relative to the rest of the date, except for seconds. The problem now is that the keys of each group in the array (3 groups) are just named 0, 1, 2 etc. and I want them to be named to the date they represent which they have been grouped by already. , I managed to solve it with just _.groupBy and momentjs.
code :
const sortByMinute = _.groupBy(messages, function (date) {
  return moment(date.createdAt*1000).startOf("minute").format();
});
Google dashboard with filters from grouped data - how to chart grouped data

Google dashboard with filters from grouped data - how to chart grouped data


By : Wawan Clalluu Merrii
Date : March 29 2020, 07:55 AM
I wish did fix the issue. I found a workaround, you should use the chartWrapper without the dashboard, so you can pass a dataTable as parameter:
Related Posts Related Posts :
  • Running two PHP versions on the same server (STRETCH)
  • Checking if a file has been selected for upload
  • Model not updating laravel
  • How to add a description of words from text to an array, to an array key by passing words?
  • Nginx rewrite rule not not passing variables if "/" is at the end of the url
  • Modify decimal point and thousands separator without changing the number of decimals
  • Remove PHP errors from CLI and PHPMyAdmin
  • Yii2 rest api - Url manager add parameters
  • 1-query batch update array of users using PDO
  • Keep getting error: implode(): Invalid arguments passed when updating data
  • Laravel 5.4 - Correct Validation rule for a required parameter that can be zero
  • What does this code mean: $objPHPExcel->getActiveSheet()->toArray(null, true,true,true)
  • Data not being added to mysql table but echo's the data?
  • While fetch row in PHP
  • IP long string filter
  • How to view first image in list per user as its highlight Profile
  • Insert multiple rows from array
  • PHP : How to remove a duplicate array item ONCE
  • Print the input box text as simple text instead of html tag
  • How to read a string variable in php as $_GET or $_POST?
  • MySQL query fetch array not working
  • LogicException with message '... must return a relationship instance.'
  • PHP - create new array with only selected keys from an existing array
  • How to allow backgrounding a process to survive a session termination?
  • How to redirect to Home page (Default page) in zend framework 2?
  • I want to call a jquery variable in php syntax
  • Disabling the default /?add-to-cart= animation on buttons in Woocommerce
  • How to use query data for another sql query in yii2
  • Replace string enclosed in specified characters based on data type
  • Symfony FormType: how to get prototype in form type file
  • Handle reply messages properly after some operations in php
  • PHP Changed Domain, how to remove old Session Cookies
  • mysqli_stmt::bind_param(): Number of variables doesn't match number of parameters in prepared statement in php
  • Error: Call to a member function update() on array laravel
  • How to change the format of a float number?
  • run ajax requests by order
  • Wordpress Install 404 Error (Cannot view login in browser)
  • Calcinai xero-php pass config once
  • Fatal error calling to undefined function in PHP file
  • Laravel hasMany and belongsTo parameters
  • How do I call a Controller method in php Laravel?
  • How to replace "@" post tag with regex in PHP?
  • Laravel : when insert record in table. How can i add that Record in the list without querying the db
  • It is possible that I could user email address to get customer id from simPRO API?
  • PHP add and merge sql result
  • laravel ckeditor dark theme
  • Laravel belongsToMany not working
  • laravel 5.4 datatables not working jquery $ referenceError
  • Zend Form 2 multiselect field is empty after validation
  • PHP - Laravel 5 get data to html table from 3 SQL database tables with column DATA as headers
  • Can't use token authorization with Laravel Passport
  • splitting lines of dates and presenting in desired format
  • Laravel 5.2 Heroku Deployment Failed to install system packages
  • Laravel relationships - are there multiple *unnecessary* database calls?
  • htaccess rewrite rule for serving index.php from parent directory
  • PHP/MongoDB - $concat aggregation
  • Remove ajax.googleapis.com from my Wordpress site
  • Image saved always empty with Storage::put in Laravel
  • How to count and sort data in junction table
  • Get common number of values in a single array
  • shadow
    Privacy Policy - Terms - Contact Us © voile276.org