Configure 2d php array - php

I'm trying to adjust a php chart library on my code with some data fetched from a database. I am too close but i think i am confused with all these arrays. I will try to explain as easy as possible. The appropriate form of constructing the data that my library needs to read in order to create a php chart is the following:
//With this value my api displays the chart normally
$p->data = array(array(array("2015/10/10",44),array("2015/10/11",56)));
The way i'm trying to construct the aforementioned array is the following
//Fetch results from database and push values into an array
while($row = mysqli_fetch_array($result)){
$values[] = array($row['Date'] => $row['Total']);
}
$p->data = array(array($values));
But unfortunately the chart is not displaying my values. How can i fix my code in order to achive this format:
$p->data = array(array(array("2015/10/10",44),array("2015/10/11",56)));

You are inserting $row['Date'] as the key and $row['Total'] as the value, which, if you run print_r($p->data) results in this:
Array
(
[0] => Array
(
[0] => Array
(
[0] => Array
(
[2015/10/10] => 44
)
[1] => Array
(
[2015/10/11] => 56
)
)
)
)
You actually need
while($row = mysqli_fetch_array($result)){
$values[] = array($row['Date'], $row['Total']);
}
This way, you will get this array:
Array
(
[0] => Array
(
[0] => Array
(
[0] => Array
(
[0] => 2015/10/10
[1] => 44
)
[1] => Array
(
[0] => 2015/10/11
[1] => 56
)
)
)
)
Exactly what you need

If the array should be the same as the first code example, you don't need the =>. So, you can just do the following:
while($row = mysqli_fetch_array($result)){
$values[] = array($row['Date'], $row['Total']);
}
The => creates a key value pair with the first item as the key and the second as the value. If you use a ,, it creates a flat array with those items as values.

You're wrapping one too many arrays:
$p->data = array(array(array("2015/10/10",44),array("2015/10/11",56)));
^-A ^-B ^-C0 ^-C1
and then
$values[] = array($row['Date'] => $row['Total']);
^-C0,C1,C2,etc...
^--B
}
$p->data = array(array($values));
^--A
^---????

Related

Array values to single array using foreach loop in PHP

I am working with php and arrays, I have multiple arrays like following
Array
(
[0] => Array
(
[wallet_address] => 0x127e61982701axxxxxxxxxxxxxxxxxxxxxxxxxxx
)
[1] => Array
(
[wallet_address] => 0xf80a41eE97e3xxxxxxxxxxxxxxxxxxxxxxxxxxxx
)
[2] => Array
(
[wallet_address] => 0x24361F1602bxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
)
and so on....
And i want to make them in single array with comma like following way
$set = array("0x127e61982701axxxxxxxxxxxxxxxxxxxxxxxxxxx","0xf80a41eE97e3xxxxxxxxxxxxxxxxxxxxxxxxxxxx","0x24361F1602bxxxxxxxxxxxxxxxxxxxxxxxxxxxxx");
How can i do this ?Here is my current code but not working,showing me same result(0,1,2 keys),Where i am wrong ?
$GetUserFollower; //contaning multiple array value
$set=array();
foreach($GetUserFollower as $arr)
{
$set[]=$arr;
}
echo "<pre>";print_R($set);
The original array is an Assoc array and therefore the wallet_address needs to be addressed specifically in a loop. Or you could use the array_column() builtin function to achieve the same thing.
$GetUserFollower; //contaning multiple array value
$set=array();
foreach($GetUserFollower as $arr)
{
$set[] = $arr['wallet_address'];
}
echo "<pre>";print_r($set);
Or
$new = array_column($GetUserFollower, 'wallet_address');
print_r($new);
RESULT
Array
(
[0] => 0x127e61982701axxxxxxxxxxxxxxxxxxxxxxxxxxx
[1] => 0xf80a41eE97e3xxxxxxxxxxxxxxxxxxxxxxxxxxxx
[2] => 0x24361F1602bxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
)
Your comments are making me think you want an array without a key, which is impossible. If you do this with the example you show in your comments
$set = array("0x127e61982701axxxxxxxxxxxxxxxxxxxxxxxxxxx","0xf80a41eE97e3xxxxxxxxxxxxxxxxxxxxxxxxxxxx","0x24361F1602bxxxxxxxxxxxxxxxxxxxxxxxxxxxxx");
print_r($set);
You will see
Array
(
[0] => 0x127e61982701axxxxxxxxxxxxxxxxxxxxxxxxxxx
[1] => 0xf80a41eE97e3xxxxxxxxxxxxxxxxxxxxxxxxxxxx
[2] => 0x24361F1602bxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
)

php get values from array json output

When I use the code below:
print_r($jsoni);
$badge_url = "http://api.steampowered.com/ISteamUserStats/GetGlobalAchievementPercentagesForApp/v0002/?gameid=841370%3Fkey&steamids=76561198108211948&fbclid=IwAR0B4wUlosbqFElHBJw-AkLwb3mGsv42xKdtrEAarDmD97Ur3AprrkW4tCk";
$jsoni = json_decode(file_get_contents($badge_url), true);
I get the following as a result:
Array
(
[achievementpercentages] => Array
(
[achievements] => Array
(
[0] => Array
(
[name] => GAME_GREEN_LIGHT
[percent] => 70.9000015259
)
[1] => Array
(
[name] => CAREER_EARN_BADGE
[percent] => 62.2999992371
)
How can I get it so that it only shows the name and the percentage?
print_r($jsoni['achievementpercentages']['achievements'])
You could loop through the decoded data to create an associative array with the achievement names as keys and the percentages as values:
$achievements = [];
foreach($jsoni['achievementpercentages']['achievements'] as $achievement)
$achievements[$achievement['name']] = $achievement['percent'];
Which outputs:
Array
(
[GAME_GREEN_LIGHT] => 70.9000015259,
[CAREER_EARN_BADGE] => 62.2999992371
)
So im now using the following code.
<?php
$achievements = [];
foreach($jsoni['achievementpercentages']['achievements'] as $achievement)
$achievements[$achievement['name']] = $achievement['percent'];
print_r($achievements);
?>
wich results in
Array ( [GAME_GREEN_LIGHT] => 70.9000015259 [CAREER_EARN_BADGE] => 62.2999992371
how do i get it to show a list from top to bottom instead of in a cluster of text?
Thanks for the help!

PHP - Dealing with duplicated array keys (internal pointers)

I have the following lines of code that fetches some data from my database. I need to reference some specific contents of the data but I am having an issue with duplicated array keys. i do not want to sort through the data using SQL statements due to the complexity of the project.
Upon checking the pointers of the array, the following was generated.
( [0] => 0 ) Array ( [0] => 0 ) Array ( [0] => 0 ) Array ( [0] => 0 ) Array ( [0] => 0 ) Array ( [0] => 0 ) Array ( [0] => 0 ) Array ( [0] => 0 )
A sample of the printed array :
( [0] => 3371450.18 ) Array ( [0] => 54459051.95 ) Array ( [0] => 210382.52 ) Array ( [0] => 6860440.01 ) Array ( [0] => 13131358.12 )
Since all the array keys are duplicated some PHP array functions like(array_sum, array_max) etc do work on the array and its getting really frustrating.
I wonder if this is because of the while loop. Are array pointers within a while loop always duplicated.
`
if(isset($_SESSION['sess']) && !empty(isset($_SESSION['sess']))){
echo "Session id is ".$_SESSION['sess']." exist";
$currentSession = $_SESSION['sess'];
$sql = "SELECT * FROM `loanbook` WHERE LoanBookSessionId='$currentSession'";
$result = mysqli_query($dbs,$sql);
$teamselection = "SELECT * FROM `Teams`";
$teamresult = mysqli_query($dbs,$teamselection);
while($row = mysqli_fetch_array($result)){
?>
<?php
$Sn[] = $row['Id'];
$Team = $row['Team'];
$CounterClass = $row['CounterPartyClassification'];
$GrossL = $row['GrossLoan'];
$CollType = $row['CollateralType'];
print_r(array_keys(array($GrossL)));
print_r((array($GrossL)));
}
?>`
It looks as if you have a 2d array, where each of the inner arrays contains a string that represents a float.
Mapping each one of the inner arrays to a parsed float value should provide the data structure you need.
<?php
$x = [
["1.43434"],
["1.43434"],
];
echo json_encode($x) . "\n";
echo json_encode(array_map(function($t) {
return floatval($t[0]);
}, $x));
output
▶ php test.php
[["1.43434"],["1.43434"]]
[1.43434,1.43434]

Looping through JSON output from Hubspot deals API

I am trying to use the Hubspot API (http://developers.hubspot.com/docs/overview) to loop through all deals and find only those which are current and then do something with those deals.
No matter what I try to do I cannot get my head around how I access the data I need - below is an example of the output.
In the API there are lots of items like dealstage below and the value field under these is what I need to access - for example in this case the deal is closedlost. Another example would be amount which would also have an entry in value so I can then see the deal value.
I want to loop through all deals and for each deal get the dealstage, amount, last update, owner and so on. Each of these are contained in an array of the same layout as [dealstage] below with a value
I have gotten to where I can print the dealstage value for each deal but it doesn't really help - is there a better way of doing this?
foreach ($list['deals'] as $line) {
foreach ($line['properties'] as $row => $value) {
if ($row=="dealstage") {
$stage=$value['value'];
print $stage."<br>";
}
}
}
Example array:
Array
(
[deals] => Array
(
[0] => Array
(
[portalId] => 12345
[dealId] => 67890
[isDeleted] =>
[associations] => Array
(
[associatedVids] => Array
(
[0] => 4051
)
[associatedCompanyIds] => Array
(
[0] => 23456
)
[associatedDealIds] => Array
(
)
)
[properties] => Array
(
[dealstage] => Array
(
[value] => closedlost
)
[createdate] => Array
(
[value] => 1471334633784
)
[amount] => Array
(
[value] => 1000
)
Would something like this be what you are looking for. Loop through the array picking out the items you are interested in and place them in a nice simple array for you to use later when building your email.
$for_email = array();
foreach ($list['deals'] as $line) {
$t = array();
if (isset($line['properties']['dealstage']['value'])) {
$t['dealstage'] = $line['properties']['dealstage']['value'];
}
if (isset($line['properties']['amount']['value'])) {
$t['amount'] = $line['properties']['amount']['value'];
}
if (isset($line['properties']['createdate']['value'])) {
$t['createdate'] = $line['properties']['createdate']['value'];
}
// any other data you want to capture
// put this data in the new array
$for_email[] = $t;
}
// check what the new array looks like
print_r($for_email);

Put multiple arrays in one large associative array

I am creating a set of arrays with the following loop:
$assessmentArr = explode("&", $assessmentData);
foreach($assessmentArr as $data) {
$fullArr = explode("_", $data);
// Break down to only archetype and value
$resultArr = explode("=", $fullArr[2]);
//print_r($resultArr);
}
Which produces the following results:
Array
(
[0] => community-support
[1] => 24
)
Array
(
[0] => money-rewards
[1] => 30
)
Array
(
[0] => status-stability
[1] => 15
)
Array
(
[0] => personal-professional-development
[1] => 32
)
Array
(
[0] => community-support
[1] => 9
)
Array
(
[0] => money-rewards
[1] => 12
)
Array
(
[0] => status-stability
[1] => 16
)
Array
(
[0] => personal-professional-development
[1] => 29
)
I need to combine these into one array, and where the [0] value matches, I need to add the [1] value together.
So I would like the final output to be something like:
Array
(
[community-support] => 33
[money-rewards] => 42
[status-stability] => 31
[personal-professional-development] => 61
)
I found this question: How to merge two arrays by summing the merged values which will assist me in merging and adding the values together, but I'm not sure how to go about it when the arrays aren't assigned to a variable. Is what I am trying to do possible or am I going about this the wrong way?
Don't make it complicated, just check if the results array already has an element with that key and if not initialize it otherwise add it. E.g.
(Add this code in your loop):
if(!isset($result[$resultArr[0]]))
$result[$resultArr[0]] = $resultArr[1];
else
$result[$resultArr[0]] += $resultArr[1];
Then you have your desired array:
print_r($result);
You could do it like this
$assessmentArr = explode("&", $assessmentData);
$finalArr = array();
foreach($assessmentArr as $data) {
$fullArr = explode("_", $data);
// Break down to only archetype and value
$resultArr = explode("=", $fullArr[2]);
if(array_key_exists($resultArr[1], $finalArr)){
$finalArr[$resultArr[0]] += $resultArr[1];
}else{
$finalArr[$resultArr[0]] = $resultArr[1];
}
}
First check, if the key already exists in the array, if so you add the value to the value in the final array. Otherwise you add the new index to the final array, with the value from resultArr as inital value.
... way too slow :/

Categories