json url
i wanna sort champions array. I want to sort it by "
champions -> 0 -> stats -> totalSessionsPlayed " But i can not. How can i short array ?
$url = 'https://tr.api.pvp.net/api/lol/tr/v1.3/stats/by-summoner/3800684/ranked?season=SEASON2016&api_key=RGAPI-2F65B634-F9C5-4DA7-A5E3-1D955D5D1E3B';
$content = file_get_contents($url);
$arr = json_decode($content);
$sorted = sort(array_column($arr, 'totalSessionsPlayed'));
ı found this code but ıt doesn't work.
Use usort with custom comparison function:
$champions = $arr->champions;
// usort alters the input array, no need to assign
usort($champions , function($a, $b) {
// Will sort in descending order, for ascending, switch sides
return $b->stats->totalSessionsPlayed - $a->stats->totalSessionsPlayed;
});
Basically, you have to sort the first level of champions array and compare lower values internally.
Your code does not work, because there is no totalSessionsPlayed key in $arr array directly.
I hope this can help you.
Here I am using the nested foreach loop for the first Object and then second for the second Object .
Using the array_filter helps to remove the empty string/element. as it returns false when an empty element is present.
SORT function Returns TRUE on success or FALSE on failure.
So that's why we used the last loop to display the sorted result.
<?php
$url = 'https://tr.api.pvp.net/api/lol/tr/v1.3/stats/by-summoner/3800684/ranked?season=SEASON2016&api_key=RGAPI-2F65B634-F9C5-4DA7-A5E3-1D955D5D1E3B';
$content = file_get_contents($url);
$arr = json_decode($content);
$champions = ($arr->champions);
foreach($champions as $champion){
$champion_totalSessionsPlayed = $champion;
foreach($champion_totalSessionsPlayed as $champions_totalSessionsPlayed){
$totalSessionsPlayed = $champions_totalSessionsPlayed->totalSessionsPlayed;
$totalSessionsPlayed_array[] = $totalSessionsPlayed;
}
}
$totalSessionsPlayed = array_filter($totalSessionsPlayed_array);
sort($totalSessionsPlayed);
$arrlength = count($totalSessionsPlayed);
for($x = 0; $x < $arrlength; $x++) {
echo $totalSessionsPlayed[$x];
echo "<br>";
}
?>
Related
I am trying to merge two JSON , but instead of overwriting the value if it is found, I want to ADD the value if it is found For exemple, assuming I have tje following three values.
$a = "[{"base":"10","touch":true,"flatfooted":true}]"
$b = "[{"natural armor":"2","touch":false,"flatfooted":true}]"
$c = "[{"natural armor":"3","touch":false,"flatfooted":true}]"
I would like to get the following result:
"[{"base":"10","touch":true,"flatfooted":true},{"natural armor":"5","touch":false,"flatfooted":true}]"
But I'm getting lost in the way.
Thank you for the help.
Also, asking in advance to avoid asking in another question: How can I turn every JSON object into a different array?
Assuming the result JSON, something like
$final[0]['base'] = 10,
$final[0]['touch'] = true,
$final[0]['flatfooted'] = true,
$final[1]['natural armor'] = 5,
$final[1]['touch'] = false,
$final[1]['flatfooted'] = true
Here's a start, I can't finish it because I have to leave. Good luck!
<?php
$a = '[{"base":"10","touch":true,"flatfooted":true}]';
$b = '[{"natural armor":"2","touch":false,"flatfooted":true}]';
$c = '[{"natural armor":"3","touch":false,"flatfooted":true}]';
//Decode values to arrays and get first item.
$a = json_decode($a, true)[0];
$b = json_decode($b, true)[0];
$c = json_decode($c, true)[0];
//Put them all in a array
$abc = [$a, $b, $c];
//Compare keys of all arrays, and put the ones with no diffs in a array
$noDiff = [];
foreach ($abc as $idx => $character) {
//Skip first because we use it in the foreach
for ($i = 1; $i < count($abc); $i++) {
$diff = array_diff_key($character, $abc[$i]);
if (empty($diff)) {
$noDiff[] = $character;
$noDiff[] = $abc[$i];
}
}
//Remove item from $abc and reset index keys
array_splice($abc, $idx, 1);
}
//$noDiff will now contain array $b and $c and we know they both have the same keys.
//We need to be sure natural armor contains numeric values and that touch and flatfooted
//have both the same boolean value.
$merged = [];
$canCombine = true;
foreach ($noDiff[0] as $key => $value) {
if (!is_numeric($value) || is_numeric($noDiff[1][$key]) {
$canCombine = false;
} else {
}
}
echo "<pre>";
var_dump(
$noDiff
);
echo "</pre>";
You can turn any JSON string into an array using:
$result = json_decode($jsonString,true) ;
If you want each JSON string to end up as a separate element of an array you can use:
$final[] = json_decode($jsonString,true) ;
So, in your case you could use:
$final[] = json_decode($a,true) ;
$final[] = json_decode($b,true) ;
$final[] = json_decode($c,true) ;
Though I would recommend a loop in case you don't always have three (e.g., $a, $b & $c).
You should always check json_last_error() after each json_decode() to make sure you didn't generate an error.
Since JSON is serialized data, you need to parse the two json objects you need to merge, then add the result of any fields, then you can update the values of one of your original json objects and serialize the data.
I haven't used PHP before, but here is an article I found on parsing json objects in PHP. http://php.net/manual/en/function.json-decode.php
Hope that helps.
1) Same AC bonuses DO NOT stack. That means you can't add two natural armors for one unit. You can however do (base + dexterity + natural + size + armor + shield)
2) Why are "touch" and "flat footed" booleans? You just add different subsets of AC
touch = base + dexterity + natural + size
flat footed = base + armor + shield
3) In case you are indeed talking about DnD, I hope you want to make a tool for yourself and your friends to use, cause you can't just publish a tool for DnD, it's copyrighted.
I have an array.First i want to search a specific value in that array and want to return that value with multiple by a value.I was trying below way but in this way its multiple with array keys but i want it will multiple with arrays value. It can be very simple but i don't know the solution.
<?php
$arr = ['10','20','30','40'];
$searching = array_search("30", $arr);
if ($searching) {
$result = $searching*30;
echo $result;
}
?>
Output is : 60
But i want : 900
The array_search() function search an array for a value and returns
the key.
Try this:
array_search give you the index, so use $arr[$searching].
$arr = ['10','20','30','40'];
$searching = array_search("30", $arr);
if ($searching) {
$result = $arr[$searching] * 30;
echo $result;
}
in_array function will help you to determine if value exists in your array.
If it exists - return this value, multiplied by some other value.
$arr = ['10','20','30','40'];
$search_val = 20;
if (in_array($search_val, $arr)) {
echo 30 * $search_val;
}
Try it:-
<?php
$arr = ['10','20','30','40'];
$val = 20;
echo (in_array($val, $arr)) ? (30 * $val) : "";
?>
I have a table that I need to find "top trusted builder" from, Trusts are separated by " ; ", So I need to pull all the data, explode the usernames, order and count them, and Im stuck on finally outputting the top username form the array, I have posted up the full segment of PHP, because im sure there has to be a much better way of doing this.
<?php
$GTB = $DBH->query('SELECT builders from griefprevention_claimdata where builders <> ""');
$GMCB->setFetchMode(PDO::FETCH_ASSOC);
$buildersarray = array();
while($row = $GTB->fetch()) {
$allbuilders = explode(";", $row['builders']);
for($i = 0; $i < count($allbuilders); $i++)
{
$buildersarray[] = $allbuilders[$i];
}
}
echo "<pre>";
print_r(array_count_values(array_filter($buildersarray)));
echo "</pre>";
?>
Outputs
Array
(
[username1] => 4
[username2] => 1
[username3] => 1
)
You can return the array from the array_count_values command into a new array called $topbuilders, and then echo out the current (first) record:
$topbuilders = array_count_values(array_filter($buildersarray));
echo current(array_keys($topbuilders)).', Rank = '.current($topbuilders);
current() will return the first item in an associative array.
Instead of using array_count_values() it would be better to use the names as the key to a frequency array:
$GTB = $DBH->query('SELECT builders from griefprevention_claimdata where builders <> ""');
$result = array();
while (($builders = $GTB->fetchColumn()) !== false) {
foreach (explode(";", $builders) as $builder) {
if (isset($result[$builder])) {
$result[$builder]++;
} else {
$result[$builder] = 1;
}
}
// sort descending based on numeric comparison
arsort($result, SORT_NUMERIC);
echo "Name = ", key($result), " Count = ", current($result), "\n";
I've been searching and trying for hours, I want to look for duplicates in my variables which print numbers and then eliminate the duplicates leaving just original numbers.
Here is what I've been trying:
$priceminpps = get_field('price_minpps');
$pricemaxpps = get_field('price_maxpps');
$priceminunit = get_field('price_minunit');
$pricemaxunit = get_field('price_maxunit');
$find_duplicates = array($priceminpps, $pricemaxpps, $priceminunit, $pricemaxunit, );
$result = array_unique($find_duplicates);
print($result);
But it doesn't work, can anyone help?
Double check if array_unique doesn't do what it should.
If it's realy array_unqiue() i would generate a new array and push the unique numbers in this new one. You can check if it's already in the new array with in_array(number-to-check, $array).
If in_array() doesn't return true, add it to the unique-number-array.
Example:
$result = array();
foreach ($find_duplicates as $number) {
if(!in_array($number, $result)) {
$result[] = $number;
}
}
$arr[] = $new_item;
Is it possible to get the newly pushed item programmatically?
Note that it's not necessary count($arr)-1:
$arr[1]=2;
$arr[] = $new_item;
In the above case,it's 2
end() do the job , to return the value ,
if its help to you ,
you can use key() after to petch the key.
after i wrote the answer , i see function in this link :
http://www.php.net/manual/en/function.end.php
function endKey($array){
end($array);
return key($array);
}
max(array_keys($array)) should do the trick
The safest way of doing it is:
$newKey = array_push($array, $newItem) - 1;
You can try:
max(array_keys($array,$new_item))
array_keys($array,$new_item) will return all the keys associated with value $new_item, as an array.
Of all these keys we are interested in the one that got added last and will have the max value.
You could use a variable to keep track of the number of items in an array:
$i = 0;
$foo = array();
$foo[++$i] = "hello";
$foo[++$i] = "world";
echo "Elements in array: $i" . PHP_EOL;
echo var_dump($foo);
if it's newly created, you should probably keep a reference to the element. :)
You could use array_reverse, like this:
$arr[] = $new_item;
...
$temp = array_reverse($arr);
$new_item = $temp[0];
Or you could do this:
$arr[] = $new_item;
...
$new_item = array_pop($arr);
$arr[] = $new_item;
If you are using the array as a stack, which it seems like you are, you should avoid mixing in associative keys. This includes setting $arr[$n] where $n > count($arr). Stick to using array_* functions for manipulation, and if you must use indexes only do so if 0 < $n < count($arr). That way, indexes should stay ordered and sequential, and then you can rely on $arr[count($arr)-1] to be correct (if it's not, you have a logic error).