count from several multidimensional arrays - php

i have foreach, which generate following arrays:
==== array 1 ====
array
0 =>
array
'tag' => string 'daf' (length=3)
1 =>
array
'tag' => string 'daa' (length=3)
2 =>
array
'tag' => string 'daf' (length=3)
3 =>
array
'tag' => string 'daaa' (length=4)
4 =>
array
'tag' => string 'daf' (length=3)
5 =>
array
'tag' => string 'daa' (length=3)
6 =>
array
'tag' => string 'daf' (length=3)
7 =>
array
'tag' => string 'daf' (length=3)
8 =>
array
'tag' => string 'daf' (length=3)
9 =>
array
'tag' => string 'abd' (length=3)
10 =>
array
'tag' => string 'abdaa' (length=5)
11 =>
array
'tag' => string 'abda' (length=4)
==== array 2 ====
array
0 =>
array
'tag' => string 'daf' (length=3)
1 =>
array
'tag' => string 'test1' (length=5)
As output i want to get something like:
array
'daf' => '7'
'daa' => '2'
'daaa' => '1'
'abd' => '1'
'abdaa' => '1'
'abda' => '1'
'test1' => '1'
The value of the new array is the count of the element from all aray generatet from the loop. array_count_values() doesn't work here...any suggestions, how to solve the problem?

Did not notice it was 2 dimensional array.
Here is another code.
var_export(
array_count_values(
call_user_func_array('array_merge', array_merge($array1, $array2))
)
);

Something a bit like this should work:
$result = array();
foreach (array_merge($array1, $array2) as $item) {
$name = $item['tag'];
if (!isset($result[$name])) {
$result[$name] = 0;
}
$result[$name]++;
}

Let's make some use of the Standard PHP Library (SPL).
You can "flatten" an array with an RecursiveArrayIterator and RecursiveIteratorIterator. As a result you get an iterator that visits each leaf of your n-dimensional array and still let's you access the actual key of the element. In the next step concat both RecursiveIteratorIterators with an AppendIterator acting like a single interator that visits each element in all of its inner (appended) iterators.
$ai = new AppendIterator;
$ai->append(new RecursiveIteratorIterator(new RecursiveArrayIterator($array1)));
$ai->append(new RecursiveIteratorIterator(new RecursiveArrayIterator($array2)));
$counters = array();
foreach($ai as $key=>$value) {
if ( 'tag'===$key ) {
// # because I don't care whether this array element exists beforehand or not.
// $value has to be something that can be used as an array key (strings in this case)
#$counters[$value] += 1;
}
}
If you want you can even use a FilterIterator instead of the if('tag'===$key). But imho this doesn't increase the readability/value of the code ;-)

Related

php array count values in 4 deep array

Im trying to count how many times a delivery date is in my array but i seem to only be able to count the first level.
array (size=48)
'2000-01-01' =>
array (size=2)
'date' => string '2000-01-01' (length=10)
0 =>
array (size=2)
'van' => string '0' (length=1)
0 =>
array (size=619)
'drop' => string '0' (length=1)
0 =>
array (size=29)
'id' => string '18137' (length=5)
'order_number' => string '13550' (length=5)
'reference' => string '' (length=0)
'delivery_date' => string '2000-01-01' (length=10)
I've tried:
$counts = array_count_values(array_flip(array_column($output, 'delivery_date')));
and
$array = array_map(function($element){
return $element['delivery_date'];
}, $output);
$array2 = (array_count_values($array));
print_r($array2);
in the end i either end up with a array to string error or the value 1.
how Would i go about counting these?
Thanks.
You could make use of array_walk_recursive and increment an array value every time the delivery_date key is present in the array at any level:
$counts = [];
array_walk_recursive(
$output,
static function ($value, string $key) use (&$counts): void {
if ($key === 'delivery_date') {
$counts[$value] = ($counts[$value] ?? 0) + 1;
}
}
);

Convert array index to custom value?

I have an array $indexedarray
printr($indexedarray) gives something like this
array (size=3)
0 => string 'Homes' (length=5)
1 => string 'Apartments' (length=10)
2 => string 'Villas' (length=6)
I want to change this arrays index also same as value, like
array (size=3)
'Homes' => string 'Homes' (length=5)
'Apartments' => string 'Apartments' (length=10)
'Villas' => string 'Villas' (length=6)
is it posssible??
You can use array_combine:
$indexedarray= ['Homes', 'Apartments', 'Villas'];
print_r(array_combine($indexedarray, $indexedarray));
Gives:
Array
(
[Homes] => Homes
[Apartments] => Apartments
[Villas] => Villas
)
But be aware that your duplicate values will be dropped. Keys will be unique!
Try This :
$myArray = [
0 => 'Homes',
1 => 'Apartments',
2 => 'Villas' ];
$newArray = [];
foreach($myArray as $key => $value){
$newArray[$value] = $value;
}
var_dump($newArray);

Php Convert Multidimensional array to string

Below is my function:
public function getChildrenId(){
$child_id = array($this->db->query("SELECT customer_id
FROM " . DB_PREFIX . "customer
WHERE parent IN ( " .(int)$this->customer->getId().") "));
foreach($child_id as $id =>$value) {
$conv = json_decode(json_encode($value), true);
$final = array_slice($conv,2);
foreach ($final as $gchildren => $key) {
sort($key);
$gr = array_slice($key,0,$this->INF);
}
}
return $gr;
}
It outputs:
array (size=3)
0 =>
array (size=1)
'customer_id' => string '2' (length=1)
1 =>
array (size=1)
'customer_id' => string '4' (length=1)
2 =>
array (size=1)
'customer_id' => string '7' (length=1)
I am trying to get the values of the nested arrays. When I use foreach I only get data from array[0]. I also tried slicing the parent array and still didn't get it right, it outputs array,array,array.
I would like to extract these arrays values to a new array that I can use to query the database. final_array = array (2,4,7).
Thank you in advance!
If your array looks like this, then the foreach should create the array your looking for.
array (size=3)
0 =>
array (size=1)
'customer_id' => string '2' (length=1)
1 =>
array (size=1)
'customer_id' => string '4' (length=1)
2 =>
array (size=1)
'customer_id' => string '7' (length=1)
The following php will output array(2,4,7);
<?php
$aNewArray = array();
foreach($aArray as $aArray){
$aNewArray[] = $aArray['customer_id'];
}
var_dump($aNewArray);
?>
You dont need a multidimensional array for this though.

php Get all values from multidimensional associative array

how can i get all values from multidimensional associative array
I dont want to use print_r want to control my array put all the value in normal array with unique values
my array is look like this
array (size=10)
0 =>
array (size=3)
0 =>
array (size=1)
'Campaign' => string 'DEMO' (length=4)
1 =>
array (size=1)
'Campaign' => string 'Home_Sec' (length=8)
2 =>
array (size=1)
'Campaign' => string '' (length=0)
1 =>
array (size=0)
empty
2 =>
array (size=0)
empty
3 =>
array (size=1)
0 =>
array (size=1)
'Campaign' => string 'Back_Brace' (length=10)
4 =>
array (size=2)
0 =>
array (size=1)
'Campaign' => string 'Home_Sec' (length=8)
1 =>
array (size=1)
'Campaign' => string '' (length=0)
5 =>
array (size=1)
0 =>
array (size=1)
'Campaign' => string 'home_Sec_2' (length=10)
6 =>
array (size=1)
0 =>
array (size=1)
'Campaign' => string 'Burial_Ins' (length=10)
7 =>
array (size=0)
empty
8 =>
array (size=0)
empty
9 =>
array (size=0)
empty
I dont want to use print_r want to control my array put all the value in normal array with unique values
array_walk is an option, but here's another option if you want to try something a bit more coded by yourself, solving this problem recursively
This will flatten any n-max level array into a single array that contains all the values of all the sub arrays (including the initial array itself)
<?php
$array = array(
1 => array(1, 2, 3, 4 => array(
1, 2, 3, 4
)),
4, 5);
function recurse_values($array) {
if (is_array($array)) {
$output_array = array();
foreach ($array as $key=>$val) {
$primitive_output = recurse_values($val);
if (is_array($primitive_output)) {
$output_array = array_merge($output_array, $primitive_output);
}
else {
array_push($output_array, $primitive_output);
}
}
return $output_array;
}
else {
return $array;
}
}
print_r(recurse_values($array));
?>
If you need unique values, at the end you can add a array_unique to do this.
You can use array_walk
$array = array(...); //your values here
function output($item, $key) {
echo $key . ' =>' . $item;
}
array_walk($array, 'output');
Are you asking how you can "flatten" this multi-dimensional array into a one dimension? Possible solutions to similar problems... How to Flatten a Multidimensional Array?

Find all second level keys in multi-dimensional array in php

I want to generate a list of the second level of keys used. Each record does not contain all of the same keys. But I need to know what all of the keys are. array_keys() doesn't work, it only returns a list of numbers.
Essentially the output Im looking for is:
action, id, validate, Base, Ebase, Ftype, Qty, Type, Label, Unit
I have a large multi-dimensional array that follows the format:
Array
(
[0] => Array
(
[action] => A
[id] => 1
[validate] => yes
[Base] => Array
(
[id] => 2945
)
[EBase] => Array
(
[id] => 398
)
[Qty] => 1
[Type] => Array
(
[id] => 12027
)
[Label] => asfhjaflksdkfhalsdfasdfasdf
[Unit] => asdfas
)
[1] => Array
(
[action] => A
[id] => 2
[validate] => yes
[Base] => Array
(
[id] => 1986
)
[FType] => Array
(
[id] => 6
)
[Qty] => 1
[Type] => Array
(
[id] => 13835
)
[Label] => asdssdasasdf
[Unit] => asdger
)
)
Thanks for the help!
<?php
// Gets a list of all the 2nd-level keys in the array
function getL2Keys($array)
{
$result = array();
foreach($array as $sub) {
$result = array_merge($result, $sub);
}
return array_keys($result);
}
?>
edit: removed superfluous array_reverse() function
array_keys(call_user_func_array('array_merge', $a));
Merge all values and retrieve the resulting keys.
One liner:
$keys=array_unique(array_reduce(array_map('array_keys',$data),'array_merge',[]));
Or in a function:
function get_array_children_keys($data) {
return array_unique(
array_reduce(array_map('array_keys', $data), 'array_merge', [])
);
}
Now lets break this down with an example, here is some sample data:
[
['key1' => 0],
['key1' => 0, 'key2' => 0],
['key3' => 0]
]
Starting with the inner most function, we run array_map with the array_keys function:
array_map('array_keys', $data)
This gives us the keys of from all child arrays
[
['key1'],
['key1', 'key2'],
['key3']
]
Then we run the array_reduce on the data with the array_merge callback and an empty array as the initial value:
array_reduce(..., 'array_merge', []);
This converts our multiple arrays into 1 flat array:
[
'key1',
'key1',
'key2',
'key3'
]
Now we strip out our duplicates with array_unique:
array_unique(...)
And end up with all our keys:
[
'key1',
'key2',
'key3'
]
foreach($bigArray as $array){
foreach($array as $key=>$value){
echo $key;
}
}
That should do what you want.
What about something like this :
$your_keys = array_keys($your_array[0]);
Of course, this is considering all sub-arrays have the same keys ; in this case, you only need the keys of the first sub-array (no need to iterate over all first-level sub-arrays, I guess)
And, as a shortened / simplified example :
$your_array = array(
array(
'action' => 'A',
'id' => 1,
'base' => array('id' => 145),
),
array(
'action' => 'B',
'id' => 2,
'base' => array('id' => 145),
),
array(
'action' => 'C',
'id' => 3,
'base' => array('id' => 145),
)
);
$your_keys = array_keys($your_array[0]);
var_dump($your_keys);
Will get you :
array
0 => string 'action' (length=6)
1 => string 'id' (length=2)
2 => string 'base' (length=4)
You can the use implode to get the string you asked for :
echo implode(', ', $your_keys);
will get you :
action, id, base
ie, the list of the keys of the first sub-array.
function __getAll2Keys($array_val){
$result = array();
$firstKeys = array_keys($array_val);
for($i=0;$i<count($firstKeys);$i++){
$key = $firstKeys[$i];
$result = array_merge($result,array_keys($array_val[$key]));
}
return $result;
}
try this function. It will return as you want.
While #raise answers provides a shortcut, it fails with numeric keys. The following should resolve this:
$secondKeys=array_unique(call_user_func_array('array_merge', array_map('array_keys',$a)));
array_map('array_keys',$a) : Loop through while getting the keys
...'array_merge'... : Merge the keys array
array_unique(... : (optional) Get unique keys.
I hope it helps someone.
UPDATE:
Alternatively you can use
$secondKeys=array_unique(array_merge(...array_map('array_keys', $a)));
That provides same answer as above, and much faster.
My proposal, similar to this answer but faster and using spread operator (PHP 5.6+).
array_merge(...array_values($fields))
if you want move names to array values and reset keys to 0..n just use array_keys in last step.
array_keys(array_merge(...array_values($fields)))
Maybe you can use array_map function, which allows you to avoid array iteration and return an array with the keys you need as values.
will be like this
$newArray = array_map(function($value){return array_keys($value);},$yourArray);
var_dump($newArray);
array (size=2)
0 =>
array (size=9)
0 => string 'action' (length=6)
1 => string 'id' (length=2)
2 => string 'validate' (length=8)
3 => string 'Base' (length=4)
4 => string 'EBase' (length=5)
5 => string 'Qty' (length=3)
6 => string 'Type' (length=4)
7 => string 'Label' (length=5)
8 => string 'Unit' (length=4)
1 =>
array (size=9)
0 => string 'action' (length=6)
1 => string 'id' (length=2)
2 => string 'validate' (length=8)
3 => string 'Base' (length=4)
4 => string 'FType' (length=5)
5 => string 'Qty' (length=3)
6 => string 'Type' (length=4)
7 => string 'Label' (length=5)
8 => string 'Unit' (length=4)
With this function you can get all keys from a multidimensional array
function arrayKeys($array, &$keys = array()) {
foreach ($array as $key => $value) {
$keys[] = $key;
if (is_array($value)) {
$this->arrayKeys($value, $keys);
}
}
return $keys;
}
Only if all records have the same keys you could do:
$firstItem = reset($array);
$keys = array_keys($firstItem);
Obviously, this is not the correct answer to this specific question, where the records have different keys. But this might be the question you find when looking how to retrieve second level keys from an array where all keys are the same (I did). If all the record have the same keys, you can simply use the first item in the array with reset() and get the keys from the first item with array_keys().

Categories