I have below type of array, now I want to get count of it's subarray
For example I want to get count key 7 & 8. How to do it ? Any solution for that ? I tried but but no success :(
Array
(
[0] => stdClass Object
(
[id] => 4
[Blogdata] => stdClass Object
(
[7] => Array
(
[0] => stdClass Object
(
[blog_id] => 105
)
)
[8] => Array
(
[0] => stdClass Object
(
[blog_id] => 101
)
)
)
)
)
$date_count = array();
foreach($FeaturedBlogs as $Key=>$date) {
foreach($date as $d) {
$key = array_keys($d); // get our date
// echo $key;echo "<br>";
print_r($d);
$date_count[$key[0]]++;
}
}
Try this....
//Count Sub Array
$final_array = [];
$x = 0;
function countSubArray($data)
{
global $final_array;
global $x;
foreach($data as $key)
{
if(is_array($key))
{
$final_array[$x][0] = "1";
$final_array[$x][1] = json_encode($key);
$final_array[$x][2] = count((array)$key);
$x++;
countSubArray($key);
}
if(is_object($key))
{
$final_array[$x][0] = "2";
$final_array[$x][1] = json_encode($key);
$final_array[$x][2] = count((array)$key);
$x++;
countSubArray($key);
}
}
}
// Call Function...
countSubArray($arr); // what array you count..
// Display Sub Array Count...
$t_count = 0;
foreach($final_array as $d)
{
if($d[0] == 1)
{
echo "Array Count :".$d[2]." Array : ".$d[1]."<br>";
$t_count++;
}
}
echo "Total Array Count :".$t_count;
output of this example is...
Array
(
[0] => stdClass Object
(
[id] => 4
[Blogdata] => stdClass Object
(
[7] => Array
(
[0] => stdClass Object
(
[blog_id] => 135
)
)
[8] => Array
(
[0] => stdClass Object
(
[blog_id] => 101
)
)
)
)
)
Array Count :1 Array : [{"blog_id":135}]
Array Count :1 Array : [{"blog_id":101}]
Total Array Count :2
Updated Answer
This is going to use a function as it's own callback function. The function will loop through an object or an array and test each element to see if it is another object or array.
If it did find a new object or array, then the function calls itself again to perform the same operations on the element, effectively traversing through your entire array.
When it has found the bottom of each element it will return the value of the counter which was keeping track of how many arrays it came across.
Like so:
function arrayCounter($data){
//At this point we have an array or an object.
//Lets loop across the elements and see if we have any more nested arrays or objects.
foreach($data as $key){
$count = 0;
//Test each element to see if it's an object or an array.
if(is_array($key) || is_object($key)){
//If it is we are going to send the element through another instance of the function.
$count += arrayCounter($key);
}
//If the element is an array we are going to increment the counter.
if(is_array($key)){
$count++;
}
}
return $count;
}
$count = arrayCounter($data);
echo 'Count: ' . $count; //Using your data this will return "2".
Hope it helps!
Related
I am developing a Bio-metric election system but i am facing problem regarding election results.
I got this array after executing a query.
Array
(
[paty1] => Array
(
[NA122] => stdClass Object
(
[count] => 2
)
[NA2] => stdClass Object
(
[count] => 0
)
[NA56] => stdClass Object
(
[count] => 1
)
)
[party2] => Array
(
[NA122] => stdClass Object
(
[count] => 0
)
[NA2] => stdClass Object
(
[count] => 0
)
[NA56] => stdClass Object
(
[count] => 0
)
)
)
This array is stored in $data and it can have unlimited indexes.
Now if count of [Paty1][NA122] is greater then count of [Party2][NA122] so i will declare Party1 win in NA122 and i have to compare it with n number of indexes.
e.g. there is another index pary3 so firstly I will compare count of [party1][NA122] with [party2][NA122] and then with [party3][NA122] and winner will be the one with greater count . Can you please help me??
Thanks in advance
Try this:
foreach(current($Result) as $Const=>$val){
echo "Winner of Constituency '$Const': ". findWinner($Const,$Result).PHP_EOL;
}
function findWinner($Const, $Result){
$Max = 0;
$Winner = '';
foreach($Result as $Party => $ConstList){
if($ConstList[$Const]->count>$Max){
$Max = $ConstList[$Const]->count;
$Winner = $Party;
}
}
return $Winner;
}
Check live code here:
https://www.tehplayground.com/x5sPu7JxuexOdwU8
So you want to get the party with the max count for a given NA#.
You can use a function like this:
function maxParty($data, $na) {
$max = null;
foreach($data as $party => $values) {
if(is_null($max)) {
$max = $party;
continue;
} else {
if($values[$na]->count > $data[$max][$na]->count) {
$max = $party;
}
}
}
return $max;
}
Then you feed this function with a $data array and the NA# you want to calculate the max party with. For example
$winner = maxParty($data, 'NA122');
It will return the key for the winner party. I.e. "party1"
Do you mean something like this:
<?php
$data=getData();
$maxValue;
$maxKey;
foreach($data as $key => $paty)
if(!isset($maxValue) || $paty->count>$maxValue){
$maxValue=$paty->count;
$maxKey=$key;
}
echo "$maxValue $maxKey";
function getData(){
$a=array();
for($i=1;$i<100;$i++)
$a["paty$i"]=(object) array("count"=>$i);
return $a;
}
?>
Explanation:
getData returns an array like the one you described
foreach($data as $key => $paty) - iterates through the entire array
if ( ) -- checks if the current value is greater than the previous max
If you want to know more about PHP:
foreach, objects, arrays and google
What I'm trying to do:
Get results from the database.
Get required values by assigning to an stdClass.
Put those objects in array. (<-The problem)
And output as JSON.
The objects are fine they get correct values. But when they are assigned to the array once, they replace all previous array values.
I'm using CodeIgniter to do the DB stuff.
The function:
function get_prizes(){
//All prize objects are stored here
$prizes = array();
//Prize object
$prize = new stdClass();
$prize->name1 = '';
//$prize->type = '';
//Getting the prizes from a simple database table
$query = $this->db->get('prizes');
if($query->num_rows() > 0){
foreach ($query->result() as $row):
$prize_name = $row->prize_name;
$prize->name1 = $prize_name;
//$prize->type = $prize_name;
$prizes[] = $prize;
echo " Item: " . print_r($prizes, true) . "<br>";
endforeach;
}
echo json_encode($prizes);
}
Output:
Item: Array ( [0] => stdClass Object ( [name1] => Radio ) )
Item: Array ( [0] => stdClass Object ( [name1] => Television ) [1] => stdClass Object ( [name1] => Television ) )
Item: Array ( [0] => stdClass Object ( [name1] => Toaster ) [1] => stdClass Object ( [name1] => Toaster ) [2] => stdClass Object ( [name1] => Toaster ) )
[{"name1":"Toaster"},{"name1":"Toaster"},{"name1":"Toaster"}]
I've tried array_push(). Also does the same thing.
You need to instantiate the object inside foreach loop:
function get_prizes()
{
// All prize objects are stored here
$prizes = array();
// Getting the prizes from a simple database table
$query = $this->db->get('prizes');
if ($query->num_rows() > 0) {
foreach($query->result() as $row):
// Prize object
$prize = new stdClass();
// $prize->type = '';
$prize->name1 = $row->prize_name;
$prizes[] = $prize;
endforeach;
}
echo json_encode($prizes);
}
I have an array, I applied in_array function to find a specific number in that array, but it's showing no result, the data is inside the array but no response..:(
Array:
Array
(
[0] => SimpleXMLElement Object
(
[0] => 572140
)
[1] => SimpleXMLElement Object
(
[0] => 533167
)
[2] => SimpleXMLElement Object
(
[0] => 572070
)
[3] => SimpleXMLElement Object
(
[0] => 572383
)
[4] => SimpleXMLElement Object
(
[0] => 285078
)
[5] => SimpleXMLElement Object
(
[0] => 430634
)
}
CODE I AM USING:
if(in_array('285078',$arr))
{
echo 'yes';
}
else
{
echo "No";
}
This is the array I am creating from the xml file..
$arr = array();
foreach($xmlInjury as $data)
{
array_push($arr,$data->player_id);
}
It's only showing 'NO'.. please help me on this...
You need to cast them all first, then search. Like this:
$new_arr = array_map(function($piece){
return (string) $piece;
}, $arr);
// then use in array
if(in_array('285078', $new_arr)) {
echo 'exists';
} else {
echo 'does not exists';
}
First, your array is not array of strings, it's array of objects.
If you can't change the structure of array try this:
foreach ($your_array as $item) {
if (strval($item) == '25478') {
echo 'found!';
break;
}
}
If you can change your array, add items to it like this:
$your_array[] = strval($appended_value);
After that you can use in_array.
in_array is not recursive, it searches only on first level.
and first level member of you array are SimpleXMLElement Objects, not an numbers.
Try with typecasting your array :-
$array = (array) $yourarray;
if(in_array('285078',$arr))
{
echo 'yes';
}
else
{
echo "No";
}
I'm trying to use a specific object type from a JSON feed, and am having a hard time specifying it. Using the code below I grab and print the specific array (max) I want,
$jsonurl = "LINK";
$json = file_get_contents($jsonurl,0,null,null);
$json_output = json_decode($json,true);
$max_output = $json_output["max"];
echo '<pre>';
print_r($max_output);
echo '</pre>';
And from the Array below, all I want to work with is the [1] objects in each array. How can I specify and get just those values?
Array
(
[0] => Array
(
[0] => 1309924800000
[1] => 28877
)
[1] => Array
(
[0] => 1310011200000
[1] => 29807
)
[2] => Array
(
[0] => 1310097600000
[1] => 33345
)
[3] => Array
(
[0] => 1310184000000
[1] => 33345
)
[4] => Array
(
[0] => 1310270400000
[1] => 33345
)
[5] => Array
(
[0] => 1310356800000
[1] => 40703
)
Well you could fetch those values with array_map:
$max_output = array_map(function($val) { return $val[1]; }, $json_output["max"]);
This requires PHP 5.3, if you use an earlier version, then you can use create_function to achieve similar results:
$max_output = array_map(create_function('$val', 'return $val[1];'), $json_output["max"]);
When you need to create new array which will contain only second values, you may use either foreach loop which will create it or use array_map() (just for fun with anonymous function available since php 5.3.0):
$newArray = array_map( function( $item){
return $item[1]
},$array);
Then you want to use last ("max" -> considering array with numeric keys) item, you can use end():
return end( $item);
And when you can process your data sequentially (eg. it's not part of some big getData() function) you can rather use foreach:
foreach( $items as $key => $val){
echo $val[1] . " is my number\n";
}
After you get $max_output...
for( $i = 0; $i < length( $max_output ); $i++ ) {
$max_output[$i] = $max_output[$i][1];
}
try this:
$ones = array();
foreach ($max_output as $r)
$ones[] = $r[1];
i want to do this type
in my form i have check box array and the function i want to call as the size of check box array,
now all is ok simple one time calling.
but i want to call the function as above,
and store the function return value in one array
as function return array so i want to do like
this
for user id 1->callfunction return array
user id 2->callfunction return array
....
....
i have try to used the array_push but i does not get any result
here is my code
$track = array();
for($i=0;$i<sizeof($usr);$i++)
{
if (!empty($start) and !empty($end))
{
$track_e = $tracker->getProjectTrack($id, $usr[$i], $taski, $start, $end);
//$track = $tracker->getProjectTrack($id, $usr, $taski, $start, $end);
}
$track=array_push($track,$track_e);
}
if you want to go through array, use foreach
$track = array();
if (!empty($start) and !empty($end)){
foreach ($usr as $u){
array_push($track,$tracker->getProjectTrack($id, $u, $taski, $start, $end);
}
}
Solution:
$track=array_push($track,$track_e);
array_push doesn't return an array; it returns the new number of elements in the array, modifying the array it receives as an argument in-place. It's actually much easier to just write:
$track []= $track_e;
Suggestion:
for($i=0;$i<sizeof($usr);$i++) {
# ...
$track_e = $tracker->getProjectTrack($id, $usr[$i], $taski, $start, $end);
Why not simplify the process of indexing $usr and counting the number of elements in it like so:
foreach ($usr as $usr_elem) {
# ...
$track_e = $tracker->getProjectTrack($id, $usr_elem, $taski, $start, $end);
Array ( [0] => Array ( [0] => 5 ) [1] => Array ( [0] => 6 ) [2] => Array ( [0] => 7 ) )
instead of this it returns
Array ( [0] => Array ( [0] => Array ( [0] => 7 ) ) [1] => Array ( [0] => Array ( [0] => 9) ) )
something like that
so i want to return it in as same first one.