How to count items in an array that's in an array? - php

How do you count items in an array that's part of an array? I'm using Advance Custom Fields plugin in WordPress and my array print_r(get_field('irl_today_entry')) output looks like this:
Array
(
[0] => Array
(
[acf_fc_layout] => irl_today_website_entry
[irl_today_website] => Array
(
[0] => Array
( data removed)
[1] => Array
( data removed )
)
)
[1] => Array
(
[acf_fc_layout] => irl_today_social_entry
[irl_today_social] => Array
(
[0] => Array
( data remove )
[1] => Array
( data remove)
)
)
)
How do you only count items in [irl_today_social]? I've tried a lot of options that do not work.

If you have multiple entries with irl_today_social you might also use array_map and array_column
$res = array_map(function($x) {
return count($x);
}, array_column($arrays, "irl_today_social"));
print_r($res);
Output
Array
(
[0] => 2
)
See a php demo

You can use array_reduce,
array_reduce(get_field('irl_today_entry'),function($a,$b){
return count($a["irl_today_website"]) + count($b["irl_today_website"]);
});

Loop through your array, get the count of your desired index, and add that to a counter.
$count = 0;
foreach(get_field('irl_today_entry') as $entry){
$count = $count + count(entry['irl_today_social']);
}

Simply you can use "Count" Function
Here is the Solution:
Step 1: First get your array items of ['irl_today_entry'].
Step 2 Then Count your ['irl_today_social'] items.
Example:
foreach(get_field('irl_today_entry') as $entry){
$socialData = count(entry['irl_today_social']);
}
Thanks

according to my understaing just simply try this
echo count($your_array[1]['irl_today_social']);

Related

Searching all values from a specific Index in multidimensional, associative Array in php by Index, not by value

with some help of this forum i found a way to get an array that perfectly fits my task. I ran into a follow-up problem tho:
I got the following example-array
Array (
[A] => Array (
[D] => Array (
[A] => Array (
[M] => Array (
[result] => ADAM )
[N] => Array (
[result] => ADAN )
)
)
)
[H] => Array (
[E] => Array (
[N] => Array (
[R] => Array (
[Y] => Array (
[result] => HENRY )
)
[N] => Array (
[E] => Array (
[S] => Array (
[result] => HENNES )
)
)
)
)
)
)
Where the Letters are Indexes and i end up with an result array for each name.
Now i am looking for a way to Search this array with a specific search-string and it should be possible from the 3rd Char on. So if i Search for 'ADA' i want to get the value from all following result-arrays which would be "ADAM" and "ADAN" as both follow on Array['A']['D']['A'].
I didnt have any trouble starting to search at the right Index but i cant figure out a way to access all 'result'-arrays. Only found ways to search for the final Value (ADAM, ADAN) but as statet im looking for all final values possible from my searchpoint.
So basically i want to get all Values from the result arrays following the last Char from my Search-String as Index of my Array. Hopefully that explanation points out what im looking for.
Thanks in Advance!
In short:
//my Input
$searchstring = 'ADA';
//Output i want
"ADAM", "ADAN";
//Input
$searchstring = 'ADAM';
//Output
"ADAM"
EDIT: I edited this question with my approach so far as a comment pointed out i should do this (thanks for that! ) so i tried to go this way:
When i had my Example-Array i tried to only select the necessary part of the structure:
$searchquery = 'HEN';
//Searchquery as Array
$check = str_split($searchquery);
//second isntance of the original array which is named $result
$finalsearch = $result;
foreach($check as $key) {
$finalsearch = $finalsearch[$key];
}
//check with output if i selected the right area
print_r($finalsearch);
Output i got from this:
Array ( [R] => Array ( [Y] => Array ( [result] => HENRY ) ) [N] => Array ( [E] => Array ( [S] => Array ( [result] => HENNES ) ) ) )
So i am in the right are of the structure.
then i tried to find ways to search for all Instances of the index 'result'.
i found the following functions and approaches that all enabled me to search for a specific value but not the indexes.
$newArray = array_values($finalsearch);
array-search($searchquery, $finalsearch);
That was the Point where i started turning in circles
First part is to find the start point for the list, this is just a case of looping over each character in the search string and moving onto that value in the array.
Once you have found the start point, you can use array_walk_recursive() which will only visit the leaf nodes - so this will only be the names (in this case), so create a list of all these nodes and return them...
function getEntry ( array $result, string $search ) {
for($i = 0; isset($search[$i]); $i++){
$result = $result[$search[$i]];
}
$output = [];
array_walk_recursive($result, function ( $data ) use (&$output) {
$output[] = $data;
});
return $output;
}
$searchstring = 'ADA';
print_r(getEntry($result, $searchstring));
which should give...
Array
(
[0] => ADAM
[1] => ADAN
)
This script first iterates over the keys containing the chars of $searchstring and if it has found it and no errors were thrown, it walks the array recursively to find all result keys to add it to the $result array. After that it implodes the $result array and echos it.
$searchstring = 'HE';
for( $i = 0; $i < strlen( $searchstring ); $i++ ) {
$sub = #( isset( $sub ) ? $sub[$searchstring[$i]] : $array[$searchstring[$i]] )
or die( 'no results found' );
}
array_walk_recursive( $sub, function( $value ) use ( &$results ) {
$results[] = $value;
});
echo implode( ', ', $results );

How to attach array in php

I have an array structure like this
Array
(
[0] => Array
(
[C:/xampp/htdocs/rosoka/file] => Array()
)
[1] => Array
(
[C:/xampp/htdocs/rosoka/file/2018-03-02] => Array()
)
[2] => Array
(
[C:/xampp/htdocs/rosoka/file/2018-03-03] => Array()
)
)
how to add some an array on key specific like
[C:/xampp/htdocs/rosoka/file] => Array('duck','buffalo')
1.You can do it like below:-
$array[0]['C:/xampp/htdocs/rosoka/file'] = ['duck','buffalo'];
Output:-https://eval.in/984253
2.Or if some values are already present there:-
$array[0]['C:/xampp/htdocs/rosoka/file'][] = 'buffalo';
Output:-https://eval.in/984254
3.Or if you want to search key first and then try to add:-
foreach($array as $key=>$value){
if(array_keys($value)[0] == 'C:/xampp/htdocs/rosoka/file'){
$array[$key]['C:/xampp/htdocs/rosoka/file'][] = 'buffalo';
}
}
Output:-https://eval.in/984255
For your requirement, you can assign an Array value to key specific like below:
$array[0]['C:/xampp/htdocs/rosoka/file'] = Array('duck','buffalo');
$array[1]['C:/xampp/htdocs/rosoka/file/2018-03-02'] = Array('duck','buffalo');
If you use $array[0]['C:/xampp/htdocs/rosoka/file'][] at left side like this it will again become an Array, hence accessing values will be changed. There is no need of having [] again.

Calculate items of multidimensional array

I want to merge some multidimension arrays and calculate the values of their items. For example :
Array
(
[0] => Array
(
[0] => Array
(
[nr_colete] => 6
)
)
[1] => Array
(
[0] => Array
(
[nr_colete] => 22
)
)
)
I want to get a solution to combine them and get a result such as
Array
(
[0] => Array
(
[nr_colete] => 6 + 22
)
)
Is there a native php function to help me get this result ? I try to found one.
I can't think of one single php native function to do this, but you can do it very simply using a foreach loop.
$sum = 0;
foreach($array AS $k => $value) {
$sum += $value[0]['nr_colete'];
}
Here is the code in action
No native function which will do that directly.But you can use array_column() and array_sum() two native function to get your desired result.
Check below code:-
$final_array[0]['nr_colete'] = array_sum(array_column(array_column($array,0),'nr_colete'));
print_r($final_array);
Output:- https://eval.in/873338
Reference:-
array_column()
array_sum()

php - count elements in array

I am trying to count elements in an array, but it doens't work as intended:
I have a while loop, which loops through my user table:
while($refsData=$refs->fetch()){
$new_array = array($refsData['id']);
print_r($new_array);
$outcome = $rentedrefs->_paying($new_array);
}
The print_r($new_array); gives me:
Array
(
[0] => 90427
)
Array
(
[0] => 90428
)
Array
(
[0] => 90429
)
Array
(
[0] => 90430
)
Array
(
[0] => 90431
)
Array
(
[0] => 90432
)
Array
(
[0] => 90433
)
Array
(
[0] => 90434
)
Array
(
[0] => 90435
)
Array
(
[0] => 90436
)
Inside the _paying function, I count the number of values from the array:
function _paying($referrals_array){
echo count($referrals_array);
}
The problem is, that the above count($referrals_array); just gives me: 1, when it should be 10
What am I doing wrong?
You create a new array at each step of the loop. Instead it should be written like this:
$new_array = array();
while($refsData=$refs->fetch()){
$new_array[] = $refsData['id'];
// print_r($new_array);
}
$outcome = $rentedrefs->_paying($new_array);
Note that I moved the _paying call outside the loop, as it seems to be the aggregating function. If not, you'd most probably make it process $refsData['id'] instead - not the whole array.
As a sidenote, I'd strongly recommend using fetchAll() method (instead of fetch when you need to fill a collection with results of a query. It'll be trivial to count the number of the resulting array.
It works properly, in each circulation of loop you have one array, so in first you have:
Array
(
[0] => 90427
)
in 2nd:
Array
(
[0] => 90428
)
and so on.
It should work properly:
var $count = 0;
while($refsData=$refs->fetch()){
$new_array = array($refsData['id']);
$count += count($new_array);
$outcome = $rentedrefs->_paying($new_array);
}
You are creating $new_array as a new array with the single element $refsData['id']. The count of 1 is therefore correct.
To get the number of results, either use a COUNT(*) select to ask your sql server, or add a counter to your loop, like this:
$entries = 0;
while($refsData=$refs->fetch()){
$new_array = array($refsData['id']);
print_r($new_array);
$entries++;
$outcome = $rentedrefs->_paying($new_array);
}
echo $entries;
You are not adding elements to an array, but creating a new array each iteration. To add elements, just do:
$new_array[] = $refsData['id'];

PHP array problem, array_merge() does not solve the problem

How to solve array problem?
Excepted result:
Array
(
[0] => 2011/03/13
[1] => 2011/03/14
[2] => 2011/02/21
)
Failed result that I get now:
Array
(
[0] => 2011/03/13
)
Array
(
[0] => 2011/03/14
)
Array
(
[0] => 2011/02/21
)
PHP code:
<?php
function get_dir_iterative($dir='.',$exclude=array('cgi-bin','.','..')){
$exclude=array_flip($exclude);
if(!is_dir($dir)){return;}
$dh=opendir($dir);
if(!$dh){return;}
$stack=array($dh);
$level=0;
while(count($stack)){
if(false!==($file=readdir($stack[0]))){
if(!isset($exclude[$file])){
if(is_dir("$dir/$file")){
$dh=opendir("$file/$dir");
if($dh){
$d=$file;
array_unshift($stack,$dh);
++$level;
}
}else{
if(isset($d)&&$level>0){
$mod=date('Y/m/d',filemtime("$d/$file"));
$ds="$d/";
}else{
$mod=date('Y/m/d',filemtime($file));
$ds='';
}
$array=array($mod);
//$b=array_merge($array); // it doesn't solve the problem
print_r($array);
}
}
}else{
closedir(array_shift($stack));
--$level;
}
}
}
get_dir_iterative();
?>
Update:
On replacing $array=array($mod); with $array[]=$mod; does not return excepted result.
Array
(
[0] => 2011/03/13
)
Array
(
[0] => 2011/03/13
[1] => 2011/03/14
)
Array
(
[0] => 2011/03/13
[1] => 2011/03/14
[2] => 2011/02/21
)
array_merge() takes several parameters, the arrays that you want to merge, in your situation it should be:
array_merge($array, $mod);
// Or:
$array[] = $mod;
Note that you can simply add a new entry to your global array (second example) to add a value. Array_merge eats more memory than it needs.
$array=array($mod);
//$b=array_merge($array); // it doesn't solve the problem
print_r($array);
For one, array_merge requires at least two arrays to do its thing. You're only providing one, so there's nothing to merge with. Your "live" version creates a new array each time, so that's why you're getting the 'bad' output. Why not simply do
$array[] = $mod;
which'll append the file's mtime to the array on each iteration? You might want to store the file's details as well, so you know where the mtime's coming from, so
$array[$dir/$file] = $mod;
might be of more use.
You can achieve this by replacing this code: $array=array($mod); with this code: $array[]=$mod;.
Try replacing the commented out line with $b[] = $array

Categories