I have dynamically array for example like this:
[{"Name":"Sutejo","status":"Overload"},{"Name":"Paiman","status":"Overload"},{"Name":"Agung Hercules","status":"Idle"},{"Name":"Heru","status":"Busy"}]
How should i do if want to make my array become like this ? (count if status has same value and combine to be array again)
Expected output:
[{"Overload":"2"},{"Idle":"1"},{"Busy":"1"}]
So far my code just like this:
public function getData(){
$key_idle = 0;
$key_busy = 0;
$key_overload = 0;
$data = $this->queries_trend->getDataCustomer();
//print_r(json_encode($data));
foreach ($data as $key => $value) {
$val = $value['status'];
if ($val == 'Idle') {
$key_idle = $key_idle + 1;
} elseif ($val == 'Busy') {
$key_busy = $key_busy + 1;
} elseif ($val == 'Overload') {
$key_overload = $key_overload + 1;
}
}
}
You can use array_count_values function:
$statuses = array_count_values(array_column($list, 'status'));
Related
i have array:
Array ( [0] => 1 [1] => 2 [2] => 3 [3] => 7 )
how to make condition in php when looping i can get output:
$datarange = 1-3,7;
i got logic like this:
if (value of array[0] + 1) = value of array[1] {
$datarange = value of array[0] - value of array[1];
}else{
$datarange = value of array[0] , value of array[1];
}
but i dont know how to Implement that to my looping
Here's a function that will make ranges when possible in an array of numbers.
<?php
function getRange($numbers) {
$lastNumber = null;
$currentRange = [];
$ranges = [];
foreach ($numbers as $number) {
if ($lastNumber === null) { // first iteration, add the number to current range
$currentRange[] = $number;
}
else {
if ($number - $lastNumber === 1) { // if difference with last number is 1, they're consecutive
$currentRange[] = $number;
}
else { // they're not consecutive, finish current range and start a new one
$ranges[] = $currentRange;
$currentRange = [$number];
}
}
$lastNumber = $number; // set the last number to compare with the next
}
$ranges[] = $currentRange; // add last range
$rangesString = []; //
foreach ($ranges as $range) {
$str = $range[0];
if (count($range) > 1) {
$str .= "-".$range[count($range) - 1];
}
$rangesString[] = $str;
}
return implode(", ", $rangesString);
}
echo getRange([1,2,3,7]); // result = 1-3, 7
echo getRange([1,2,6,9,10,12,15,17,18,19]); // result = 1-2, 6, 9-10, 12, 15, 17-19
Try this. I have change your logic and apply it in loop. for range:
$arr = array(1,2,3,7);
$last_val = "";
$first_val = "";
$add_val = true;
foreach ($arr as $key => $value) {
if($first_val == "")
$first_val = $value;
if(isset($arr[$key+1]))
{
if($value+1 == $arr[$key+1])
{
$last_val = $arr[$key+1];
$add_val = false;
}
else
$add_val = true;
}
else
$add_val = true;
if($add_val)
{
if($last_val != "")
$datarange[] = $first_val."-".$last_val;
else
$datarange[] = $first_val;
$first_val = "";
$last_val = "";
}
}
echo implode(",", $datarange);
DEMO
I want to combine two arrays into a dictionary.
The keys will be the distinct values of the first array, the values will be all values from the second array, at matching index positions of the key.
<?php
$a=[2,3,4,5,6,7,8,9,10];
$b=[1,1,3,2,1,2,6,8,8];
?>
array_combine($b,$a);
Expected result as
<?php
/*
Value '1' occurs at index 0, 1 and 4 in $b
Those indices map to values 2, 3 and 6 in $a
*/
$result=[1=>[2,3,6],3=>4,2=>[5,7],6=>8,8=>[9,10]];
?>
There are quite a few PHP array functions. I'm not aware of one that solves your specific problem. you might be able to use some combination of built in php array functions but it might take you a while to weed through your choices and put them together in the correct way. I would just write my own function.
Something like this:
function myCustomArrayFormatter($array1, $array2) {
$result = array();
$num_occurrences = array_count_values($array1);
foreach ($array1 AS $key => $var) {
if ($num_occurrences[$var] > 1) {
$result[$var][] = $array2[$key];
} else {
$result[$var] = $array2[$key];
}
}
return $result;
}
hope that helps.
$a=[2,3,4,5,6,7,8,9,10];
$b=[1,1,3,2,1,2,6,8,8];
$results = array();
for ($x = 0; $x < count($b); $x++) {
$index = $b[$x];
if(array_key_exists ($index, $results)){
$temp = $results[$index];
}else{
$temp = array();
}
$temp[] = $a[$x];
$results[$index] = $temp;
}
print_r($results);
Here's one way to do this:
$res = [];
foreach ($b as $b_index => $b_val) {
if (!empty($res[$b_val])) {
if (is_array($res[$b_val])) {
$res[$b_val][] = $a[$b_index];
} else {
$res[$b_val] = [$res[$b_val], $a[$b_index]];
}
} else {
$res[$b_val] = $a[$b_index];
}
}
var_dump($res);
UPDATE: another way to do this:
$val_to_index = array_combine($a, $b);
$result = [];
foreach ($val_to_index as $value => $index) {
if(empty($result[$index])){
$result[$index] = $value;
} else if(is_array($result[$index])){
$result[$index][] = $value;
} else {
$result[$index] = [$result[$index], $value];
}
}
var_dump($result);
I have to push an associative array in a normal array (not to convert).
Example (NO CODE):
project = {}
element["title"] = "My title"
element["description"] = "My description"
is there a way to have this
echo $project->title;
//or
echo $project[0]["title"]
?
I'v tried this, but server says: ERROR 500
$i = 0;
$projects = {};
foreach($projectsElements as $element) {
while($i <= $nRowsForProject) {
$idSection = $element->idSection;
if($idSection == 1) $elements["".$element->internalDescription.""] = $element->text;
else if($idSection == 2) $elements["".$element->internalDescription.""] = $element->text;
else if($idSection == 3) $elements["".$element->internalDescription.""] = $element->text;
$i++;
}
array_push($projects,$elements);
$i=0;
}
$projects = {}; is not valid php.
If you want to initialize an empty array (associative or numeric, that does not matter), you need:
$projects = [];
or on older php versions:
$projects = array();
Also note that you need to do the same to your $elements array at the beginning of each iteration otherwise it will grow on every iteration. Assuming that the descriptions are not all the same...
foreach($projectsElements as $element) {
$elements = [];
while($i <= $nRowsForProject) {
...
And your while loop does not seem to make a lot of sense: You are not using the $i variable in your loop so are just doing the same assignments on each iteration.
$projects = []; // declare empty array
foreach($projectsElements as $element) {
$projects []= $element; // push $element into $projects array
}
$i = 0;
$projects = array();
foreach($projectsElements as $element) {
while($i <= $nRowsForProject) {
$elements = array();
$idSection = $element->idSection;
if($idSection == 1) $elements["".$element->internalDescription.""] = $element->text;
else if($idSection == 2) $elements["".$element->internalDescription.""] = $element->text;
else if($idSection == 3) $elements["".$element->internalDescription.""] = $element->text;
$i++;
}
array_push($projects,$elements);
$i=0;
}
I have an array with about 360 keys:
$threadColours['Apricot'] = array(250,180,160,3341,328,826,194,3332,0);
$threadColours['Apricot, Light'] = array(255,230,225,3824,8,833,2605,-1,1);
$threadColours['Apricot, Medium'] = array(255,135,105,3340,329,827,193,-1,2);
I am retrieving a pixel rgb values that came from this array. So I need to get the key where, for example, $threadColours[???][0]=250, [1]=180, [2]=160. I know you can search for a single key but I cannot figure out how to match multiple values. Just to be clear, I have the rgb values I just want to know how to get the key that has all three values in [0],[1],[2] respectively.
Thank you much,
Todd
function getColourKey($colours, $r, $g, $b) {
foreach ($colours as $key => $value)
if ($value[0] == $r && $value[1] == $g && $value[2] == $b)
return $key;
return NULL;
}
You can use code like this:
$threadColours['Apricot'] = array(250,180,160,3341,328,826,194,3332,0);
$threadColours['Apricot, Light'] = array(255,230,225,3824,8,833,2605,-1,1);
$threadColours['Apricot, Medium'] = array(255,135,105,3340,329,827,193,-1,2);
$needle=array(2605,-1,1); // this is your r,g,b
$startIndex = -1;
$rootElem = "";
foreach ($threadColours as $key => $arr) {
for ($i=0; $i < count($arr); $i+=3) {
if ( $arr[$i] == $needle[0] &&
$arr[$i+1] == $needle[1] &&
$arr[$i+2] == $needle[2]
) {
$rootElem = $key;
$startIndex = $i;
break;
}
}
}
printf("rootElem=[%s], startIndex=[%s]\n", $rootElem, $startIndex);
OUTPUT:
rootElem=[Apricot, Light], startIndex=[6]
$search = array(250, 180, 160);
$color = null;
foreach ($threadColours as $key => $val) {
if (array_slice($val, 0, 3) == $search) {
$color = $key;
break;
};
}
I need to transform my nested sets structure (mysql) into json for this spacetree
1) http://blog.thejit.org/wp-content/jit-1.0a/examples/spacetree.html
I found this function to create an array from nested sets:
2) http://semlabs.co.uk/journal/converting-nested-set-model-data-in-to-multi-dimensional-arrays-in-php
I can also convert php array into json with PHP function json_encode
My problem: the function nestify (from second link) gives me not exactly that i need. I need something like this: http://pastebin.com/m68752352
Can you help me change the function "nestify" so it gives me the correct array?
Here is this function one more time:
function nestify( $arrs, $depth_key = 'depth' )
{
$nested = array();
$depths = array();
foreach( $arrs as $key => $arr ) {
if( $arr[$depth_key] == 0 ) {
$nested[$key] = $arr;
$depths[$arr[$depth_key] + 1] = $key;
}
else {
$parent =& $nested;
for( $i = 1; $i <= ( $arr[$depth_key] ); $i++ ) {
$parent =& $parent[$depths[$i]];
}
$parent[$key] = $arr;
$depths[$arr[$depth_key] + 1] = $key;
}
}
return $nested;
}
The following snippet should do the trick, adapted from some PHP Doctrine code I found on the web :
function toHierarchy($collection)
{
// Trees mapped
$trees = array();
$l = 0;
if (count($collection) > 0) {
// Node Stack. Used to help building the hierarchy
$stack = array();
foreach ($collection as $node) {
$item = $node;
$item['children'] = array();
// Number of stack items
$l = count($stack);
// Check if we're dealing with different levels
while($l > 0 && $stack[$l - 1]['depth'] >= $item['depth']) {
array_pop($stack);
$l--;
}
// Stack is empty (we are inspecting the root)
if ($l == 0) {
// Assigning the root node
$i = count($trees);
$trees[$i] = $item;
$stack[] = & $trees[$i];
} else {
// Add node to parent
$i = count($stack[$l - 1]['children']);
$stack[$l - 1]['children'][$i] = $item;
$stack[] = & $stack[$l - 1]['children'][$i];
}
}
}
return $trees;
}