Array
(
[university] => 57
[iit] => 57
[jee] => 44
[application] => 28
[study] => 26
[college] => 23
[exam] => 19
[colleges] => 19
[view] => 19
[amp] => 18
)
How can I get an array with the first 5 elements?
Use array_slice() function:
$newArray = array_slice($originalArray, 0, 5, true);
If you need the first 5 elements
by order of keys: use ksort(),
by order of values: use sort()
before the array_slice(). Insert a letter 'r' to the second place for reverse order: krsort(), arsort().
Related
I have an array of php like this
Array
(
[0] => Array
(
[Sr_No] => 1
[Asan_Category] => Warm-Up
[Asan_Cat_Val] => 8
[Asan_Sub_Category] => Ankle
[Asan_Sub_Cat_Val] => 35
[Asan_Name] => General Ankle Warm up
[Asan_Name_Val] => 447
[Prescribed_Steps] => 40
[Prescribed_Ratio] => 00
[Actual_Steps] => 12
[Actual_Ratio] => 0
)
[1] => Array
(
[Sr_No] => 2
[Asan_Category] => Warm-Up
[Asan_Cat_Val] => 8
[Asan_Sub_Category] => Knee
[Asan_Sub_Cat_Val] => 111
[Asan_Name] => General knee warm up
[Asan_Name_Val] => 464
[Prescribed_Steps] => 20
[Prescribed_Ratio] => 00
[Actual_Steps] => 14
[Actual_Ratio] => 0
)
[2] => Array
(
[Sr_No] => 1
[Asan_Category] => Warm-Up
[Asan_Cat_Val] => 8
[Asan_Sub_Category] => Ankle
[Asan_Sub_Cat_Val] => 35
[Asan_Name] => General Ankle Warm up
[Asan_Name_Val] => 447
[Prescribed_Steps] => 40
[Prescribed_Ratio] => 00
[Actual_Steps] => 10
[Actual_Ratio] => 0
)
[3] => Array
(
[Sr_No] => 2
[Asan_Category] => Warm-Up
[Asan_Cat_Val] => 8
[Asan_Sub_Category] => Knee
[Asan_Sub_Cat_Val] => 111
[Asan_Name] => General knee warm up
[Asan_Name_Val] => 464
[Prescribed_Steps] => 20
[Prescribed_Ratio] => 00
[Actual_Steps] => 9
[Actual_Ratio] => 0
)
)
The desired output I want
Array
(
[0] => Array
(
[Asan_Id] => 447
[Asan_Category] => Warm-Up
[Asan_Sub_Category] => Ankle
[Asan_Name] => General Ankle Warm up
[Prescribed_Steps] => 40
[Prescribed_Ratio] => 00
[Total_Steps] => 22
)
[1] => Array
(
[Asan_Id] => 464
[Asan_Category] => Warm-Up
[Asan_Sub_Category] => Knee
[Asan_Name] => General knee warm up
[Prescribed_Steps] => 20
[Prescribed_Ratio] => 00
[Total_Steps] => 23
)
)
I want those data who are repeating become one but their different actual steps become total steps with their sum.
Please help me because I have tried some code but did not success like this
$asan=[];
$total_steps=0;
foreach ($aasan_details as $key) {
$total_steps += $key['Actual_Steps'];
if(!in_array($key['Asan_Name_Val'],$asan))
{
$asan[] = $key['Asan_Name_Val'];
$lookup[] = array("Asan_Id"=>$key['Asan_Name_Val'],
"Asan_Category"=>$key['Asan_Category'],
"Asan_Sub_Category"=>$key['Asan_Sub_Category'],
"Asan_Name"=>$key['Asan_Name'],
"Prescribed_Steps"=>$key['Prescribed_Steps'],
"Prescribed_Ratio"=>$key['Prescribed_Ratio'],
'Total_Steps'=>$total_steps);
}
}
It is not working , what should I do guys , please help me out
where $aasan_details is the array which I showed above and the in lookup array I am getting uniqe values but not getting their total
The best solution would be to move this into a database and use a query to perform that exact operation for you.
But if you have to do it in code, you could use a keyed array to basically group them up by however many fields need to match for them to be conjoined:
e.g.
foreach ..
$consolidated[$item['Asan_Cat_Val']][$item['Asan_Sub_Cat_Val']][] = $item;
Then make a couple of nested loops to go across this and sum everything up.
There a few useful techniques to explain here...
You can reduce eye-strain in your looped array declarations by establishing a collection of keys that you know you want to retain in (copy to) the output array. This spares you having to type out each $keyName => $row[$keyName], like this (but ultimately make yourself happy).
Declare temporary associative keys (using $id) while building your output array to allow isset() to make super fast checks for a pre-existing group.
If a group is not yet set, then store the data with the new keys along with the data with the original keys. No arithmetic is necessary. The + symbols in my snippet are not "addition operators", they are "array union operators" -- they are merging the three arrays without a function call (otherwise array_merge() would do the same).
When finished iterating the array, you may choose to re-index the result (remove the temporary associative keys) by calling array_values(). If you are not bothered by the existence of these temporary keys, you can omit the function call.
If a group has been encountered before, you only need to modify the Total_steps. Use an addition-assignment operator (+=) for the briefest syntax.
Code: (Demo)
$keysToKeep = array_flip(['Asan_Category', 'Asan_Sub_Category', 'Asan_Name', 'Prescribed_Steps', 'Prescribed_Ratio']);
foreach ($array as $row) {
$id = $row['Asan_Name_Val'];
if (!isset($result[$id])) {
$result[$id] = ['Asan_Id' => $id] + array_intersect_key($row, $keysToKeep) + ['Total_Steps' => $row['Actual_Steps']];
} else {
$result[$id]['Total_Steps'] += $row['Actual_Steps'];
}
}
var_export(array_values($result));
Output:
array (
0 =>
array (
'Asan_Id' => '447',
'Asan_Category' => 'Warm-Up',
'Asan_Sub_Category' => 'Ankle',
'Asan_Name' => 'General Ankle Warm up',
'Prescribed_Steps' => '40',
'Prescribed_Ratio' => '00',
'Total_Steps' => 22,
),
1 =>
array (
'Asan_Id' => '464',
'Asan_Category' => 'Warm-Up',
'Asan_Sub_Category' => 'Knee',
'Asan_Name' => 'General knee warm up',
'Prescribed_Steps' => '20',
'Prescribed_Ratio' => '00',
'Total_Steps' => 23,
),
)
I have this array built from a function that sorts allowed or valid url slugs and their ids into another array. I can call the current category id by passing the url slug to the category. Now I need to get the children category ids (if any) so i can call the appropriate items from the database for display purpose.
Heres an example of the array:
Array (
[radios] => 1
[radios/motorola] => 2
[radios/motorola/handheld] => 3
[radios/motorola/mobile] => 4
[radios/icom] => 5
[radios/icom/handheld] => 6
[radios/icom/mobile] => 7
[radios/mics-and-speakers] => 8
[radios/mounts] => 9
[radios/radio-other] => 10
[misc] => 11
[misc/led] => 12
[phones] => 13
[phones/samsung] => 14
[phones/lg] => 15
[phones/motorola] => 16
[phones/huawei] => 17
[phones/blackberry] => 18
[phones/flip] => 19
[boosters] => 20
[boosters/standalone] => 21
[boosters/indoor-antenna] => 22
[boosters/outdoor-antenna] => 23
[boosters/connections] => 24
[accessories] => 25
[accessories/cases] => 26
[accessories/other] => 27
[internet] => 28
[internet/fusion] => 29
[internet/point-to-point] => 30
[internet/hotspots] => 31
[internet/gateways] => 32
[internet/switches] => 33
[cameras] => 34
[cameras/complete-kits] => 35
[cameras/additional-cameras] => 36
[cameras/other] => 37
);
As you can see, each result points to the category ID of that group. If i visit the following url:
http://example.com/store/cameras
I can print out that THE PATH CURRENTLY IS: 34 which is correct. Since It has children under it, I also need their ID's and the ID's of any of their children, etc etc. That way on radios, i can show ALL of the sub category items, and on radios/motorola i am only showing the Motorola based items and its children, and such down the line.
If there an easy way, using this array I have now, to sort the children (if any) all the way down and get back just their id's (preferably in a new array) for showing database items?
You might want to create a function like this to filter your array,
function filterArray($array, $term) {
$pattern = "/\b" . str_replace($term, '/', '\/') . "\b/i";
foreach($array as $key => $value) {
if(preg_match($pattern, $key)) {
/* Following condition makes sure that your search
will match starting from the beginning. */
if (stripos(trim($key), $term) === 0){
$filtred[] = $value;
}
}
}
}
Then call the above function with the $array and your search $term.
filterArray($array, 'radios') will give you this,
Array ( [0] => 1 [1] => 2 [2] => 3 [3] => 4 [4] => 5 [5] => 6 [6] => 7 [7] => 8 [8] => 9 [9] => 10 )
filterArray($array, 'radios/motorola') will give you this,
Array ( [0] => 2 [1] => 3 [2] => 4 )
And so on.. I hope this helps.
You can maybe try double layer array, so that you can store values like this,
Array (
[name] => John
[surname] => Smith
[contact] => Array (
[address] => 18 Maple Street
[number] => 555 477 77 77
)
)
This way if you need to print something from "contact" you can use a loop and print all childs of contact field.
i have an array in which each key it has another array.
What i want to do is to store those values in different arrays.
For example, the original array looks like the following:
Array
(
[0] => Array
(
[concurso] => 2758
[R1] => 12
[R2] => 20
[R3] => 33
[R4] => 46
[R5] => 50
[R6] => 51
[R7] => 54
)
[1] => Array
(
[concurso] => 2759
[R1] => 12
[R2] => 15
[R3] => 31
[R4] => 50
[R5] => 54
[R6] => 55
[R7] => 11
)
[2] => Array
(
[concurso] => 2760
[R1] => 4
[R2] => 11
[R3] => 12
[R4] => 40
[R5] => 45
[R6] => 51
[R7] => 55
)
.
.
.
[29] => Array
(
[concurso] => 2787
[R1] => 3
[R2] => 5
[R3] => 19
[R4] => 24
[R5] => 28
[R6] => 30
[R7] => 15
)
)
And for each key i want to store the corresponding values in different arrays (where 'concurso' will be the key of each new array and its corresponding Rn value):
R1:
Array
(
[2758] => 12
[2759] => 12
[2760] => 4
...
[2787] => 3
)
R2:
Array
(
[2758] => 20
[2759] => 15
[2760] => 11
...
[2787] => 5
)
R3:
Array
(
[2758] => 33
[2759] => 31
[2760] => 12
...
[2787] => 19
)
R4:
Array
(
[2758] => 46
[2759] => 50
[2760] => 40
...
[2787] => 24
)
R5:
Array
(
[2758] => 50
[2759] => 54
[2760] => 45
...
[2787] => 28
)
R6:
Array
(
[2758] => 51
[2759] => 55
[2760] => 51
...
[2787] => 30
)
...
Rn:
How do i achieve this? I guess i need to create variable names dynamically, since the number of elements of a given array may change depending on the data retrieved.
What do you suggest?
I am trying this code but no luck so far:
$ultimos_sorteos_m,true); //this is the big array shown above
foreach($ultimos_sorteos_m as $key1 => $last_sorteos){
$contador=count($last_sorteos); //how many items the current sub-array has
$k=1; //an index
echo '<p>the number of items is '.$contador.'</p>';
foreach($last_sorteos as $key=>$valor){
if($key=='concurso'){
$concurso=$valor;
echo 'concurso: '.$concurso.' <br>'; //to get the 'concurso' that will work as a key for the other arrays
}
//storing here the rest of the values
if(substr( $key, 0, 1 ) === "R" && substr($key, 1, 1)===$k){
//i don't know here how to store the values in different arrays
echo 'storing value: '.$valor.'<br>';
$Ritems[$concurso]=$valor; //the problem is that only store the last value
}
}
}
If you want to know why, I want it this way in order to graph those data by using the phpgraphlib graphing library. It will be a graph showing different lines.
Try this : This creates variable names dynamically so you dont need to know the number for R1,R2,R3 etc elements you have
<?php
foreach($ultimos_sorteos_m[0] as $key1 => $last_sorteos){
$$key1 = array_column($ultimos_sorteos_m, $key1 , 'concurso'); // This is a dynamic variable name. See http://php.net/manual/en/language.variables.variable.php
}
var_dump($R1);
var_dump($R2);
?>
Please comment if you see a problem. Thanks!
Like this?
foreach($orig_array[0] as $key => $_)
$new_array[$key] = array_column($orig_array, $key, 'concurso');
array_column
shim for php < 5.5
If you're absolutely sure you need R1, R2 as variables (you don't), you can extract() the array afterwards.
You can use array_column. Try this if your PHP version 5.5+
$R1 = array_column($arr, 'R1', 'concurso');
.
.
.
$R7 = array_column($arr, 'R7', 'concurso');
I have the following output of an array using PHP. I need to do two things... First, I need to sort the array so it prints by the most recent date. I can't use a simple sort, because the date is outputted in the format mm/dd/yyyy (and not a regular time stamp) ...
Then I need to count how many rows exist for each year.
So, in the example below, I would need to know that there are ...
2 entries from 2010
2 entries from 2011
1 entry from 2012
Stop counting when there are no more rows
Since the year is not separate from the rest of the date digits, this also complicates things...
Array
(
[0] => Array
(
[racer_date] => 11/15/2010
[racer_race] => Test Row 4
[racer_event] => 321
[racer_time] => 16
[racer_place] => 12
[racer_medal] => 1
)
[1] => Array
(
[racer_date] => 7/15/2010
[racer_race] => Test Row 3
[racer_event] => 123
[racer_time] => 14
[racer_place] => 6
[racer_medal] => 0
)
[2] => Array
(
[racer_date] => 7/28/2011
[racer_race] => Test Row
[racer_event] => 123
[racer_time] => 10
[racer_place] => 2
[racer_medal] => 2
)
[3] => Array
(
[racer_date] => 10/9/2011
[racer_race] => Test Row 2
[racer_event] => 321
[racer_time] => 12
[racer_place] => 3
[racer_medal] => 3
)
[4] => Array
(
[racer_date] => 10/3/2012
[racer_race] => World Indoor Championships (final)
[racer_event] => 400m
[racer_time] => 50.79
[racer_place] => 1
[racer_medal] => 1
)
)
function cmp($a, $b)
{
if (strtotime($a["racer_date"]) == strtotime($b["racer_date"])) {
return 0;
}
return (strtotime($a["racer_date"]) < strtotime($b["racer_date"])) ? -1 : 1;
}
usort($array, "cmp");
call your array $array, and above code will sort it..
And to count entities you'll need to run foreach and check date('Y',strtotime($a["racer_date"])) in that foreach which will give you year in 4 digit..
$arr =array(
28 => 23,
26 => 23,
15 => 12,
29 => 12,
1 => 12,
16 => 15,
30 => 15,
11 => 12,
8 => 23,
33 => 23
);
how to sort like this :
8 => 23
26 => 23
28 => 23
33 => 23
16 => 15
30 => 15
1 => 12
11 => 12
15 => 12
29 => 12
Use uksort, but make the array available to the comparison function for the secondary comparison by value. Making it a global variable would be the quickest + dirtiest way.
You could use uksort() which enables the custom callback to take a look at both the keys and, indirectly, their associated values. Then it's a simple matter of deciding which comparisons to make and returning the appropriate greater-than-less-then-or-zero value to influence the sort order.
Here's an example using a closure around a temporary variable (see Jacob's comment) which should hopefully make sense.
$temp = $arr;
uksort($arr, function ($a,$b) use ($temp) {
// Same values, sort by key ascending
if ($temp[$a] === $temp[$b]) {
return $a - $b;
}
// Different values, sort by value descending
return $temp[$b] - $temp[$a];
});
unset($temp);
print_r($arr);
Its quite easy. First use ksort and then use asort for the new sorted array. You will find your result.