Count occurrences of a value inside a multidimensional array - php

so i retrieve a json, convert it into an array and i got this output:
Array
(
[Sid] => 23888555
[pages] => Array
(
[0] => Array
(
[id] => 13111071
[name] => Page 1
[slots] => Array
(
[0] => Array
(
[SlotId] => 6
[info] => Array
(
[id] => 5247
[color] => red
)
)
[1] => Array
(
[SlotId] => 4
[info] => Array
(
[id] => 5267
[color] => blue
)
)
[2] => Array
(
[SlotId] => 7
[info] => Array
(
[id] => 5267
[color] => green
)
)
)
)
[1] => Array
(
[id] => 13111072
[name] => Page 2
[slots] => Array
(
[0] => Array
(
[SlotId] => 6
[info] => Array
(
[id] => 5247
[color] => red
)
)
[1] => Array
(
[SlotId] => 4
[info] => Array
(
[id] => 5267
[color] => blue
)
)
)
)
)
)
I have no problem reading it whatsoever, what i wanna do is count for every page how many similar "last" id i got.
Exemple :
[pages][0][slots][0][info][id]
[pages][0][slots][1][info][id]
[pages][0][slots][3][info][id]
For the page 1, I wanna compare these 3 ids between them and count the occurrences.
[pages][1][slots][0][info][id]
[pages][1][slots][1][info][id]
For the page 2, I wanna compare these 2 ids between them and count the occurrences.
The output i want looks like this :
page 1 -> 1x5247
-> 2x5267
page 2 -> 1x5247
-> 1x5267
EDIT :
I tried using
foreach ($data['pages'] as $item) {
foreach ($item['slots'] as $slotnumber => $value) {
print_r(array_count_values($item['slots'][$slotnumber]['info']));
}
}
which returns me this :
Array ( [5247] => 1 [red] => 1 )
Array ( [5267] => 1 [blue] => 1 )
Array ( [5267] => 1 [green] => 1 )
So i think i might be able to use this but i don't know how.

I manually declared the array and then created the countstuff() function. This should work for you. I tested it and it work on my end. After going through all this trouble, I really do appreciated it if you choose my answer and up vote it.
<?php
$data = Array("Sid" => "23888555", "pages" => Array("0" => Array("id" => "13111071", "name" => "Page 1", "slots" => Array("0" => Array("SlotId" => "6", "info" => Array("id" => "5247", "color" => "red")), "1" => Array("SlotId" => "4", "info" => Array("id" => "5267", "color" => "blue")), "2" => Array("SlotId" => "7","info" => Array("id" => "5267", "color" => "green")))),
"1" => Array
(
"id" => "13111072",
"name" => "Page 2",
"slots" => Array
(
"0" => Array
(
"SlotId" => "6",
"info" => Array
(
"id" => "5247",
"color" => "red"
)
),
"1" => Array
(
"SlotId" => "4",
"info" => Array
(
"id" => "5267",
"color" => "blue"
)
)
)
)
)
);
//End of array declaration
//Now the really convoluted coding starts
//Create a function
function countstuff($yourarray){
foreach($yourarray as $mainarraykey => $mainarray){
if($mainarraykey == "pages"){
foreach($mainarray as $pageskey => $pagesarray){
//echo "Page \"$pageskey\"<br/>";
foreach($pagesarray as $pagessubarraykey => $pagessubarray_array){
if($pagessubarraykey == "slots"){
foreach($pagessubarray_array as $slotskey => $slots){
foreach($slots as $slotssubkey => $slotssub){
if($slotssubkey == "info"){
foreach($slotssub as $key => $value){
if($key == "id"){
//echo $value."<br/>";
$pages[$pageskey][] = $value;
}
}
}
}
}
}
}
}
}
}
return $pages;
}
//Execute the countstuff() function
$output = countstuff($data);
function showresults($input){
foreach($input as $pagekey => $page){
echo "Page $pagekey:<br/>";
$results = array_count_values($page);
foreach($results as $resultkey => $result){
echo $result."x".$resultkey."<br/>";
}
echo "<br/>";
}
}
showresults($output);
?>

I tried some things let me know what you guys think of this.
I get every id then enter them into an array then use array_count_values
$array_ids = array();
foreach ($data['pages'] as $item) {
$numberOfElements = count($item['slots']);
$z= 0;
foreach ($item['slots'] as $slotnumber => $value) {
$array_ids[$z] = $item['slots'][$slotnumber]['info']['id'];
// search for occurrences when the array is full
if (count($array_ids) == $numberOfElements) {
var_dump(array_count_values($array_ids));
// reset the array to 0 every time we loop through the whole infos
$array_ids = array();
}
$z++;
}
}
This seems to work for every page.
array (size=2)
5267 => int 2
5247 => int 1
array (size=2)
5267 => int 1
5247 => int 1

Related

make inline result from array value

I have two array as bellow :
First array :
Array
(
[0] => Array
(
[0] => Array
(
[name] => one
[number] => 051
)
[1] => Array
(
[name] => two
[number] => 052
)
[2] => Array
(
[name] => three
[number] => 053
)
)
[1] => Array
(
[0] => Array
(
[name] => four
[number] => 061
)
[1] => Array
(
[name] => five
[number] => 062
)
)
)
I want to make output from first array above
[0] => 051, 052, 053.
[1] => 061, 062.
Array
(
[0] => Array
(
[0] => Array
(
[name] => book
[number] => 41
)
[1] => Array
(
[name] => pencil
[number] => 42
)
)
[1] => Array
(
[name] => eraser
[number] => 71
)
)
I want to make output from second array above
[0] => 41, 42.
[1] => 71.
Please advise. Thank you.
You can make a try like this way with two foreach() loop.
$numbers = [];
foreach ($array as $k => $v) {
$num = [];
foreach ($v as $k2 => $v2) {
$num[] = $v2['number'];
}
$numbers[$k] = implode(',',$num).'.';
}
print_r($numbers);
DEMO: https://3v4l.org/mEeO7
you can try something like this
$arr = Array (
Array (
Array (
"name" => "one",
"number" => "051"
),
Array (
"name" => "two",
"number" => "052"
),
Array (
"name" => "three",
"number" => "053"
)
),
Array (
Array (
"name" => "four",
"number" => "061"
),
Array (
"name" => "five",
"number" => "062"
)
)
);
foreach ($arr as $k => $s_arr) {
echo "[" . $k . "] => ";
foreach ($s_arr as $k2 => $v2) {
echo $v2["number"] . " ";
}
echo "\n";
}

Make associative array of unique values from column containing arrays

Array
(
[0] => Array
(
[id] => 21153
[genre] => ["History","Drama", "Thriller"]
)
[1] => Array
(
[id] => 21152
[genre] => ["ACTION"]
)
[2] => Array
(
[id] => 21151
[genre] => ["ROMANTIC"]
)
[3] => Array
(
[id] => 21150
[genre] => ["Drama"]
)
)
I have with the above array and I want to convert that array to an unique array as mentioned below, and there should be any duplicate values.
Array(
[History] => "History"
[ACTION] => "ACTION"
[ROMANTIC] => "ROMANTIC"
[Drama] => "Drama"
[Thriller]=>"Thriller"
)
I don't really get how the resulting array makes any sense, but here you are:
Loop through the array, loop through the genres and push items to a new array.
<?
$a = Array
(
[
"id" => 21153,
"genre" => ["History","Drama", "Thriller"]
],
[
"id" => 21152,
"genre" => ["ACTION"]
]
);
$result = [];
foreach($a as $b) {
foreach($b['genre'] as $genre) {
$result[$genre] = $genre; // don't need to check if it exists already, because we'll overwrite it anyway.
}
}
echo "<pre>";
print_r($result);
echo "</pre>";
// output:
Array
(
[History] => History
[Drama] => Drama
[Thriller] => Thriller
[ACTION] => ACTION
)
It can be done by using foreach() loop and in_array() function like below
$myArray=array();
$array = array(
array("id"=>21153,"genre"=>array("History","Drama", "Thriller")),
array("id"=>21152,"genre"=>array("ACTION")),
array("id"=>21151,"genre"=>array("ROMANTIC")),
array("id"=>21150,"genre"=>array("Drama"))
);
foreach($array as $arr){
foreach($arr as $genres){
if(is_array($genres)){
foreach($genres as $elem){
if (!in_array($elem, $myArray))
{
$myArray[$elem]=$elem;
}
}
}
}
}
print_r($myArray);
This is a function that resolves what you ask, though I'm not sure it is quite useful to have value and key being identical. I'm just looping over all genders and add only the ones I don't already have store in returning array. probably a bit dangerous with your code because it is case sensitive
function getGenders(array $rawValues) :array {
$distinctGenders = [];
foreach ($rawValues as $row) {
foreach ($row["genre"] as $gender) {
if (!in_array($gender, $distinctGenders)) {
$distinctGenders[$gender] = $gender;
}
}
}
return $distinctGenders;
}
By doing the changes, I have fixed this,
$responseData = Array(
[0] => Array
(
[id] => 21153
[genre] => ["History","Drama", "Thriller"]
)
[1] => Array
(
[id] => 21152
[genre] => ["ACTION"]
)
[2] => Array
(
[id] => 21151
[genre] => ["ROMANTIC"]
)
[3] => Array
(
[id] => 21150
[genre] => ["Drama"]
)
foreach ($responseData as $data){
$strReplace = str_replace(array('[',']') , '' , $data['genre']);
$explodeData[] = explode(',', $strReplace);
}
And the output after exploding is :
$explodeData = Array
(
[0] => Array
(
[0] => "History"
[1] => "Drama"
[2] => "Thriller"
)
[1] => Array
(
[0] => "ACTION"
)
[2] => Array
(
[0] => "ROMANTIC"
)
[3] => Array
(
[0] => "Drama"
)
)
And finally by the foreach loop :
foreach ($explodeData as $arr) {
foreach ($arr as $genres) {
if (!in_array($genres, $myArray)) {
$myArray[$genres] = $genres;
}
}
}
And finally the required output comes as below :
Array(
["History"] => "History"
["Drama"] => "Drama"
["Thriller"] => "Thriller"
["ACTION"] => "ACTION"
["ROMANTIC"] => "ROMANTIC"
)
Flatten the column of data.
Assign keys from the values (this ensures uniqueness).
Code: (Demo)
$array = [
["id" => 21153, "genre" => ["History", "Drama", "Thriller"]],
["id" => 21152, "genre" => ["ACTION"]],
["id" => 21151, "genre" => ["ROMANTIC"]],
["id" => 21150, "genre" => ["Drama"]]
];
$flat = array_merge(...array_column($array, 'genre'));
var_export(
array_combine($flat, $flat)
);
Output:
array (
'History' => 'History',
'Drama' => 'Drama',
'Thriller' => 'Thriller',
'ACTION' => 'ACTION',
'ROMANTIC' => 'ROMANTIC',
)

PHP - accesing to data of multi-dimensional array

I am trying to access data in a multi-dimenstional array.
I need to get values of this data (EC000001, EG000017, EN, EF007220) but I am struggling with foreach loops in PHP, especially when need to nested foreach Could you please help me and give me solution to access wanted data?
I need to loop over all $c's and then loop inside to get all needed data.This is how I collected value EC000001 before, but I believe that there is a better solution.
foreach ($c as $classCodes => $value) {
$classCode = key($c[$classCodes]); //classCode -> EC000001
}
Structure of array:
Array
(
**[EC000001]** => Array
(
[0] => **EG000017**
[1] => Array
(
[0] => Array
(
[0] => **EN**
[1] => Busbar terminal
)
[1] => Array
(
[0] => **nl-NL**
[1] => Aansluitklem stroomrail
)
)
[2] => Array
(
[0] => Array
(
[0] => **EF007220**
[1] => EU570448
[2] => Array
(
)
)
[1] => Array
(
[0] => EF007219
[1] => EU570448
[2] => Array
(
)
)
[2] => Array
(
[0] => EF000073
[1] =>
[2] => Array
(
[0] => EV009241
[1] => EV009472
)
)
[3] => Array
(
[0] => EF007092
[1] => EU570448
)
[4] => Array
(
[0] => EF004969
[1] => EU570126
)
)
)
)
I can not test it, but you can try with this inside the loop:
$value[0]; // -> 1
$value[1][0][0]; // -> 2
$value[1][1][1]; // -> 3
$EG000002Array[0][EG000001][0]
$EG000002Array[0][EG000001][1][0]
$EG000002Array[0][EG000001][1][1][1]
there are many ways to get array values from multi dimensional array
for example using foreach():
$flavors = array('Japanese' => array('hot' => 'wasabi',
'salty' => 'soy sauce'),
'Chinese' => array('hot' => 'mustard',
'pepper-salty' => 'prickly ash'));
// $culture is the key and $culture_flavors is the value (an array)
foreach ($flavors as $culture => $culture_flavors) {
// $flavor is the key and $example is the value
foreach ($culture_flavors as $flavor => $example) {
print "A $culture $flavor flavor is $example.\n";
}
}
or using for( ) :
$specials = array( array('Chestnut Bun', 'Walnut Bun', 'Peanut Bun'),
array('Chestnut Salad','Walnut Salad', 'Peanut Salad') );
// $num_specials is 2: the number of elements in the first dimension of $specials
for ($i = 0, $num_specials = count($specials); $i < $num_specials; $i++) {
// $num_sub is 3: the number of elements in each sub-array
for ($m = 0, $num_sub = count($specials[$i]); $m < $num_sub; $m++) {
print "Element [$i][$m] is " . $specials[$i][$m] . "\n";
}
}
the output should be like :
Element [0][0] is Chestnut Bun
Element [0][1] is Walnut Bun
Element [0][2] is Peanut Bun
Element [1][0] is Chestnut Salad
Element [1][1] is Walnut Salad
Element [1][2] is Peanut Salad
You can use recursion and regex to check if it's bolded :)
Notice we put& to $classCodes to pass it by reference and not
by value.
Function:
function get_bolded_data($c, &$classCodes = array()){
foreach($c as $k1 => $v1){
if(is_array($v1)){
//If $v1 is an array we call get_bolded_data() again and pass
//$v1 and $classCode
get_bolded_data($v1,$classCodes);
}else if(preg_match("/(\*\*).*(\*\*)/", $v1)){
$classCodes[] = $v1;
}
}
}
Usage:
$classCodes = array();
$c = array(
0 => array(
'**EC000001**' => array(
0 => '**EG000017**',
1 => array(
0 => array(
0 => '**EN**',
1 => 'Busbar terminal'
) ,
1 => array(
0 => '**nl-NL**',
1 => 'Aansluitklem stroomrail'
)
) ,
2 => array(
0 => array(
0 => '**EF007220**',
1 => 'EU570448',
2 => array()
) ,
1 => array(
0 => 'EF007219',
1 => 'EU570448',
2 => array()
) ,
2 => array(
0 => 'EF000073',
1 => '',
2 => array(
0 => 'EV009241',
1 => 'EV009472'
)
) ,
3 => array(
0 => 'EF007092',
1 => 'EU570448'
) ,
4 => array(
0 => 'EF004969',
1 => 'EU570126'
)
)
)
)
);
//Call our function
get_bolded_data($c, $classCodes);
Here is the result from var_dump:
array(4) {
[0]=>
string(12) "**EG000017**"
[1]=>
string(6) "**EN**"
[2]=>
string(9) "**nl-NL**"
[3]=>
string(12) "**EF007220**"
}

getting sub array from the given array in php

I have a array variable $data which has the following array structure:
Array
(
[0] => Array
(
[rowdata] => Array
(
[0] => Array
(
[wiecont_03] =>
[tevrc_04] =>
[opmerkTXT] => Overall NPS
[0] => Array-----------------------
( |
[0] => rapport |
[1] => npsorg |
[3] => npsdetbe | i want this
part of the array
)-------------------------------
)
[1] => Array
(
[DOELGROEP] => 2
[KANTOOR] => 2
[OBLIGOCATEGORIE] => 3
[NAAM] => dfdf
[WEIGHT] => 0.95
[opmerkTXT] => Overall NPS
[0] => Array
(
[1] => npsorg
[3] => npsdetbe
)
)
)
[reason] => column values are not correct
)
)
from the above array structure i want to fetch the sub array if any as depicted by the dotted line.
Desired Output:
[0] => Array
(
[0] => rapport
[1] => npsorg
[3] => npsdetbe
)
and
[0] => Array
(
[1] => npsorg
[3] => npsdetbe
)
What i have tried: i tried array_slice() and array_chunks() but none of them worked in my case.
Thanks in advance
You also can do it(in short) like this:
Demo: https://eval.in/86588
<?php
$arr = array
(
0 => array
(
"rowdata" => array
(
"0" => array
(
"wiecont_03" => "",
"tevrc_04" => "",
"opmerkTXT" => "Overall NPS",
"0" => array
(
"0" => "rapport",
"1" => "npsorg",
"3" => "npsdetbe"
)
),
"1" => array
(
"DOELGROEP" => 2,
"KANTOOR" => 2,
"OBLIGOCATEGORIE" => 3,
"NAAM" => "dfdf",
"WEIGHT" => 0.95,
"opmerkTXT" => "Overall NPS",
"0" => array
(
"1" => "npsorg",
"3" => "npsdetbe",
)
)
)
)
);
$re = array();
//print_r($arr[0]['row_data']);
$i=0;
foreach($arr[$i]['rowdata'] as $a){
if(is_array($a[0])){
array_push($re,$a[0]);
}
$i =$i+1;
}
print_r($re);
TRY THIS:
Demo : https://eval.in/86560
$arr = array
(
"0" => array
(
"rowdata" => array
(
"0" => array
(
"wiecont_03" => "",
"tevrc_04" => "",
"opmerkTXT" => "Overall NPS",
"0" => array
(
"0" => "rapport",
"1" => "npsorg",
"3" => "npsdetbe"
)
),
"1" => array
(
"DOELGROEP" => 2,
"KANTOOR" => 2,
"OBLIGOCATEGORIE" => 3,
"NAAM" => "dfdf",
"WEIGHT" => 0.95,
"opmerkTXT" => "Overall NPS",
"0" => array
(
"1" => "npsorg",
"3" => "npsdetbe",
)
)
)
)
);
$re = array();
foreach($arr as $a){
foreach($a as $b){
foreach($b as $c){
array_push($re,$c[0]);
}
}
}
print_r($re);
OUTPUT
Array
(
[0] => Array
(
[0] => rapport
[1] => npsorg
[3] => npsdetbe
)
[1] => Array
(
[1] => npsorg
[3] => npsdetbe
)
)
Your pattern is same in all case then this function is fine
function getMyArray($array){
$rowdata = $array[0]['rowdata'];
$resultArray = array();
foreach($rowdata as $val){
$resultArray[] = $val[0];
}
return $resultArray;
}
Usage:-
$array = "YOUR ARRAY HERE";
$result = getMyArray($array);
foreach($data[0]['rowdata'] as $value){
print_r($value[0]);
}

How do I move array child value to parent key?

I need some clarity as to what PHP function can achieve what I'm aiming for.
This is a PHP array I have:
Array
(
[0] => Array
(
[id] => 6
[index] => 1
[active] => 1
[name] => MyName
)
[1] => Array
(
[id] => 1
[index] => 2
[active] => 1
[name] => YourName
)
[2] => Array
(
[id] => 2
[index] => 4
[active] => 1
[name] => TheirName
)
}
I want to take the "index" value and make it a KEY of that array parent, so the array would become this:
Array
(
[1] => Array
(
[id] => 6
[index] => 1
[active] => 1
[name] => MyName
)
[2] => Array
(
[id] => 1
[index] => 2
[active] => 1
[name] => YourName
)
[4] => Array
(
[id] => 2
[index] => 4
[active] => 1
[name] => TheirName
)
}
Can anyone please tell me how would I do this in PHP?
Thank you in advance.
you can use: array_column($array, null, 'index');
is the better solution, but only work for >= 5.5 php version
Not the most elegant solution, but it works (it doesn't actually move the array, it just generates a new one that corresponds to your requirements):
$resultArr = array();
foreach ($mainArr as $value) {
$resultArr[$value['index']] = $value;
}
unset($mainArr); // or $mainArr = $resultArr;
This way you won't overwrite any existing keys in your original array.
$a = array
(
0 => array
(
"id" => 6,
"index" => 1,
"active" => 1,
"name" => "MyName"
),
1 => Array
(
"id" => 1,
"index" => 2,
"active" => 1,
"name" => "YourName"
),
2 => Array
(
"id" => 2,
"index" => 4,
"active" => 1,
"name" => "TheirName"
)
);
$newArray = array();
foreach ($a as $foo) {
$newArray[$foo['index']] = $foo;
}
You have to do it manually with:
$input = array( /* your data */ );
$output = array();
foreach ( $input as $values ) {
$output[ $values['index'] ] = $values;
}
public static function normArray($key, $inputArray)
{
$outputArray = array();
foreach ($inputArray as $item) {
$index = intval($item[$key]);
$outputArray[$index] = $item;
}
return $outputArray;
}

Categories