I have this array written below, and I know it isnt pretty, sorry. I come to this array structure as it is the only way I could think of when dealing with my post request.
$_POST = array("person" => array(
[1] => array("id" => 1, "name" => "bob"),
[2] => array("id" => 2, "name" => "jim")
)
);
I want to be able to pick "name" from certain "id", so below code is what I came up with. In the example below, if person["id"] is equal to 1, retrieve its "name" which is "bob".
foreach ($_POST as $dataSet) {
foreach ($dataSet as $person) {
foreach ($person as $field => $value) {
if ($person["id"] == 1) {
echo $person["name"];
}
}
}
}
The problem I am having is as I execute the code.
the result is bobbob,
it seems like the code looped the if statement twice (same as the number of elements in the person array). I know if I put break into the code, then it will solve it, but anyone know why it looped twice? Maybe this will deepen my foreach and array understanding.
There is no need to have third nested loop. Hope this one will be helpful.
Problem: In the third loop you were iterating over Persons: array("id" => 1, "name" => "bob") which have two keys. and you are checking only single static key $person["id"], that's why it was printing twice.
Solution 1:
Try this code snippet here
<?php
ini_set('display_errors', 1);
$POSTData = array("person" => array(
1 => array("id" => 1, "name" => "bob"),
2 => array("id" => 2, "name" => "jim")
)
);
foreach ($POSTData as $dataSet)
{
foreach ($dataSet as $person)
{
if ($person["id"] == 1)
{
echo $person["name"];
}
}
}
Solution 2:
Alternatively you can try this single line solution.
Try this code snippet here
echo array_column($POSTData["person"],"name","id")[1];//here 1 is the `id` you want.
You must have seen the other answers, and they have already said that you dont need the 3rd loop. but still if you want to keep the third loop.
you can use this code.
foreach ($_POST as $dataSet) {
foreach ($dataSet as $person) {
foreach ($person as $field => $value) {
if($value == 1){
echo $person['name'];
}
}
}
}
No need of third foreach
<?php
$mainArr = array("person" => array(
1 => array("id" => 1, "name" => "bob"),
2 => array("id" => 2, "name" => "jim")
)
);
foreach ($mainArr as $dataSet) {
foreach ($dataSet as $person) {
if ($person["id"] == 1) {
echo $person["name"];
break;
}
}
}
?>
Live demo : https://eval.in/855386
Although it's unclear why you need to do a POST in this fashion, here's how to get "bob" only once:
<?php
$_POST = array("person" => array(
1 => array("id" => 1, "name" => "bob"),
2 => array("id" => 2, "name" => "jim")
)
);
$arr = array_pop($_POST);
foreach($arr as $a) {
if ($a["id"] == 1) {
echo $a["name"];
}
}
Array_pop() is useful for removing the first element of the array whose value is an array itself which looks like this:
array(2) {
[1]=>
array(2) {
["id"]=>
int(1)
["name"]=>
string(3) "bob"
}
[2]=>
array(2) {
["id"]=>
int(2)
["name"]=>
string(3) "jim"
}
}
When the if conditional evaluates as true which occurs only once then the name "bob" displays.
See live code.
Alternatively, you could use a couple of loops as follows:
foreach ($_POST["person"] as $data) {
foreach ($data as $value) {
if ( $value == 1) {
echo $data["name"],"\n";
}
}
}
See demo
As you mentioned, I want to be able to pick name from certain id, : No need of nested looping for that. You can do like this using array_column and array_search :
$data = array("person" => array(
1 => array("id" => 1, "name" => "bob"),
2 => array("id" => 2, "name" => "jim")
)
);
// 1 is id you want to search for
$key = array_search(1, array_column($data['person'], 'id'));
echo $data['person'][$key + 1]['name']; // $key + 1 as you have started array with 1
Output:
bob
with foreach:
foreach ($data as $dataValue) {
foreach ($dataValue as $person) {
if ($person['id'] === 1) {
echo $person["name"];
}
}
}
Related
I have an associative array in my PHP code. I want to unset all the keys that have empty value.
I know individual keys can be unset using the following code
unset($array_name['key_name']);
What I don't know is how to recursively do this with an array. While searching for an answer I came across answers recommending PHP built-in function array_filter(), however I failed to grasp how that works. So here's the code I tried to write but it doesn't work either.
<?php
function unset_all_empty_array_keys($associative_array){
foreach ($associative_array as $key => $value){
if ($value == ""){
unset($associative_array['$key']); // This doesn't work.
}
}
};
$list = array(
"item1" => "one",
"item2" => "",
"item3" => "three",
);
unset_all_empty_array_keys($list, '$list');
print_r($list);
echo "<br>";
// Manually Unsetting key-value pair works fine.
unset($list['item2']);
print_r($list);
?>
When you want do it with 'foreach()' then by reference:
function unset_all_empty_array_keys(&$associative_array){
foreach ($associative_array as $key => &$value){
if ($value == ""){
unset($associative_array[$key]);
}
}
}
The way with 'array_filter()':
$list = array_filter($list,function($a){
return $a!='';
})
And can only work 'recursively' on multi-dimensional array
$a = ['a'=>['b'=>'']];
Your example is an flat array with only one dimension.
So here the version for multi-dimensional arrays:
$list = array(
"item1" => "one",
"item2" => "",
"item3" => array(
"item1" => "one",
"item2" => "",
"item3" => "three",
)
);
function unset_all_empty_array_keys_recursive(&$associative_array){
foreach ($associative_array as $key => &$value){
if ($value == ""){
unset($associative_array[$key]);
} else if (is_array($value)){
unset_all_empty_array_keys_recursive($value);
}
}
}
unset_all_empty_array_keys($list);
var_export($list);
I have an array thusly
$main_array = [
["image" => "james.jpg", "name" => "james", "tag" => "spacey, wavy"],
["image" => "ned.jpg", "name" => "ned", "tag" => "bright"]
["image" => "helen.jpg", "name" => "helen", "tag" => "wavy, bright"]
]
I use a foreach to echo some HTML based on the value of tag. Something like this
foreach($main_array as $key => $array) {
if ($array['tag'] == "bright") {
echo '<p>'.$array['name'].' '.$array['image'].' '.$array['tag'].'</p>';
}
}
This only outputs "ned" as matching the tag "bright". But it should output "helen" too. Similarly:
foreach($main_array as $key => $array) {
if ($array['tag'] == "wavy") {
echo '<p>'.$array['name'].' '.$array['image'].' '.$array['tag'].'</p>';
}
}
Should output "james" and "helen". What kind of function do I need to achieve the desired result?
When checking an item in a list of items, you can use explode() to split it into parts (I've used split by ", " as each item seems to have a space as well) and then use in_array() to check if it is in the list...
if (in_array("bright", explode( ", ", $array['tag']))) {
You cant do it directly, because it return key with values in string. Below are the working code.
<?php
$main_array = [
["image" => "james.jpg", "name" => "james", "tag" => "spacey, wavy"],
["image" => "ned.jpg", "name" => "ned", "tag" => "bright"],
["image" => "helen.jpg", "name" => "helen", "tag" => "wavy, bright"]
];
foreach($main_array as $key => $array) {
$str_arr = explode (", ", $array['tag']);
foreach ($str_arr as $key2 => $array2) {
if ($array2 == "wavy") {
echo '<p>'.$array['name'].' '.$array['image'].' '.$array['tag'].'</p>';
}
}
}
?>
I am looking to group an array into subarrays based on its keys.
Sample Array
Array
(
[0] => Array
(
[a_id] => 1
[a_name] => A1
[b_id] => 1
[b_name] => B1
[c_id] => 1
[c_name] => C1
)
[1] => Array
(
[a_id] => 1
[a_name] => A1
[b_id] => 1
[b_name] => B1
[c_id] => 2
[c_name] => C2
)
[2] => Array
(
[a_id] => 1
[a_name] => A1
[b_id] => 2
[b_name] => B2
[c_id] => 3
[c_name] => C3
)
[3] => Array
(
[a_id] => 2
[a_name] => A2
[b_id] => 3
[b_name] => B3
[c_id] => 4
[c_name] => C4
)
)
I need this sample array to be converted into a JSON array of the following format:
Expected Output
[{
"a_id": 1,
"a_name": "A1",
"b_list": [{
"b_id": 1,
"b_name": "B1",
"c_list": [{
"c_id": 1,
"c_name": "C1"
}, {
"c_id": 2,
"c_name": "C2"
}]
}, {
"b_id": 2,
"b_name": "B2",
"c_list": [{
"c_id": 3,
"c_name": "C3"
}]
}]
}, {
"a_id": 2,
"a_name": "A2",
"b_list": [{
"b_id": 3,
"b_name": "B3",
"c_list": [{
"c_id": 4,
"c_name": "C4"
}]
}]
}]
I was able to group by a key using the code below.
$array = array(
array("a_id" => "1","a_name" => "A1","b_id" => "1","b_name" => "B1","c_id" => "1","c_name" => "C1"),
array("a_id" => "1","a_name" => "A1","b_id" => "1","b_name" => "B1","c_id" => "2","c_name" => "C2"),
array("a_id" => "1","a_name" => "A1","b_id" => "2","b_name" => "B2","c_id" => "3","c_name" => "C3"),
array("a_id" => "2","a_name" => "A2","b_id" => "3","b_name" => "B3","c_id" => "4","c_name" => "C4")
);
$return = array();
foreach($array as $val) {
$return[$val["a_id"]][] = $val;
}
print_r($return);
But my actual scenario involves grouping into sub arrays didn't worked.
Looking forward to see if there is an optimized way or useful function to get into my expected JSON response.
Note: I am looking into a generalized use case here . For example : a_list as countries,b_list as states and c_list as cities.
Man that is very specific use case for arrays. Well here is your solution.
$array = <YOUR SAMPLE ARRAY>
$output = [];
/*
* Nesting array based on a_id, b_id
*/
foreach ($array as $item) {
$aid = $item['a_id'];
$bid = $item['b_id'];
$cid = $item['c_id'];
if(!isset($output[$aid])){
$output[$aid] = [
'a_id' => $item['a_id'],
'a_name' => $item['a_name'],
'b_list' => [
$bid => [
'b_id' => $item['b_id'],
'b_name' => $item['b_name'],
'c_list' => [
$cid = [
'c_id' => $item['c_id'],
'c_name' => $item['c_name']
]
]
]
]
];
} else if (!isset($output[$aid]['b_list'][$bid])){
$output[$aid]['b_list'][$bid] = [
'b_id' => $item['b_id'],
'b_name' => $item['b_name'],
'c_list' => [
$cid => [
'c_id' => $item['c_id'],
'c_name' => $item['c_name']
]
]
];
} else if(!isset($output[$aid]['b_list'][$bid]['c_list'][$cid])) {
$output[$aid]['b_list'][$bid]['c_list'][$cid] = [
'c_id' => $item['c_id'],
'c_name' => $item['c_name']
];
} else {
// Do/Dont overrider
}
}
/*
* Removing the associativity from the b_list and c_list
*/
function indexed($input){
$output = [];
foreach ($input as $key => $item) {
if(is_array($item)){
if($key == 'b_list' || $key == 'c_list'){
$output[$key] = indexed($item);
} else {
$output[] = indexed($item);
}
} else {
$output[$key] = $item;
}
}
return $output;
}
$indexed = indexed($output);
print_r(json_encode($indexed, 128));
Interesting requirement there.
Here is my generalized solution that is also extendable.
function transform($array, $group=[
['a_id','a_name','b_list'],
['b_id','b_name','c_list'],
['c_id','c_name'],
]){
foreach($array as $a){
$r = &$result;
foreach($group as $g){
$x = &$r[$a[$g[0]]];
$x[$g[0]] = $a[$g[0]];
$x[$g[1]] = $a[$g[1]];
if(isset($g[2])) $r = &$x[$g[2]]; else break;
}
}
return transformResult($result);
}
function transformResult($result){
foreach($result as &$a)
foreach($a as &$b)
if(is_array($b)) $b = transformResult($b);
return array_values($result);
}
To extend this solution, all you have to do is modify the $group parameter,
either directly in the function declaration or by passing an appropriate value as the 2nd parameter.
Usage example:
echo json_encode(transform($array), JSON_PRETTY_PRINT);
This will return the same output assuming the same $array input in your example.
Now here is the code that works best in the given situation. I have created a similar situation and then explained the solution in detail.
Situation
The Order Form is multipage depending on the number of days served based on the package selected. Details of each package are stored in the database with the following fields:
package_id (Unique Field)
package_name (Name of the Package, e.g. Package A)
servings_count (Total Servings in a Day)
days_served (Number of Days Served in a Month)
In order to carry forward the selection of meals for each day and serving of that day to store as an Order in the database, I required a Multidimensional Array of PHP that can be defined/populated dynamically.
Expected output is something like:
Array
(
[Day 1] => Array
(
[meal_id_1] => Unique ID //to be replaced with user selection
[meal_code_1] => Meal Name //to be replaced with user selection
[meal_type_1] => Meal //prefilled based on the selected package
[meal_id_2] => Not Available //to be replaced with user selection
[meal_code_2] => 2 //to be replaced with user selection
[meal_type_2] => Meal //prefilled based on the selected package
)
[Day 2] => Array
(
[meal_id_1] => Unique ID //to be replaced with user selection
[meal_code_1] => Meal Name //to be replaced with user selection
[meal_type_1] => Meal //prefilled based on the selected package
[meal_id_2] => Not Available //to be replaced with user selection
[meal_code_2] => 2 //to be replaced with user selection
[meal_type_2] => Meal //prefilled based on the selected package
)
This above array has been created 100% dynamically based on the explained structure and number of servings and days. Below is the code with some explanation.
First, we have to declare two PHP Arrays.
$total_meals_array = []; //Primary, Multidimension Array
$meals_selected_array = []; //Meals Details Array to be used as primary array's key value.
After doing this, run MySQL query to read packages from the database. Now based on the result, do the following:
$total_meals_array = []; //Primary, Multidimension Array
$meals_selected_array = []; //Meals Details Array to be used as primary array's key value.
if( $num_row_packages >= 1 ) {
while($row_packages = mysqli_fetch_array ($result_packages)) {
$package_id = $row_packages['package_id'];
$package_name = $row_packages['package_name'];
$servings_count = $row_packages['servings_count'];
$days_served = $row_packages['days_served'];
//this for loop is to repeat the code inside `$days_served` number of times. This will be defining our primary and main Multidimensional Array `$total_meals_array`.
for ($y = 1; $y <= $days_served; $y++) {
//once inside the code, now is the time to define/populate our secondary array that will be used as primary array's key value. `$i`, which is the meal count of each day, will be added to the key name to make it easier to read it later. This will be repeated `$meals_count` times.
for ($i = 1; $i <= $meals_count; $i++) {
$meals_selected_array["meal_id_" . $i] = "Unique ID";
$meals_selected_array["meal_code_" . $i] = "Meal Name";
$meals_selected_array["meal_type_" . $i] = "Meal";
}
//once our secondary array, which will be used as the primary array's key value, is ready, we will start defining/populating our Primary Multidimensional Array with Keys Named based on `$days_served`.
$total_meals_array["Day " . $y] = $meals_selected_array;
}
}
}
That's it! Our dynamic Multidimensional Array is ready and can be viewed by simply the below code:
print "<pre>";
print_r($total_meals_array);
print "</pre>";
Thank you everyone, specially #yarwest for being kind enough to answer my question.
Here is the code, you can use it for index from a_ to y_ deep. The innerest element is null, if you don't want it. Terminate the for loop before last element, then process last element seperately. You also can do some improvement on this code. Hope this helps.
<?php
$array = array(
array("a_id" => "1","a_name" => "A1","b_id" => "1","b_name" => "B1","c_id" => "1","c_name" => "C1"),
array("a_id" => "1","a_name" => "A1","b_id" => "1","b_name" => "B1","c_id" => "2","c_name" => "C2"),
array("a_id" => "1","a_name" => "A1","b_id" => "2","b_name" => "B2","c_id" => "3","c_name" => "C3"),
array("a_id" => "2","a_name" => "A2","b_id" => "3","b_name" => "B3","c_id" => "4","c_name" => "C4")
);
$arrays = array_map(function($v){return array_chunk($v, 2, true);}, $array);
$result = [];
foreach($arrays as $value)
{
$ref = &$result;
$len = count($value);
$index = 0;
for(; $index < $len; $index++)
{
$arr = $value[$index];
$char = key($arr)[0];
$charAdd = chr(ord($char)+1);
$key = $arr[$char.'_id'].$arr[$char.'_name'];
$listKey = $charAdd.'_list';
foreach($arr as $k => $v)
{
$ref[$key][$k] = $v;
}
$ref = &$ref[$key][$listKey];
}
}
var_dump($result);
Output: the online live demo
ei#localhost:~$ php test.php
array(2) {
["1A1"]=>
array(3) {
["a_id"]=>
string(1) "1"
["a_name"]=>
string(2) "A1"
["b_list"]=>
array(2) {
["1B1"]=>
array(3) {
["b_id"]=>
string(1) "1"
["b_name"]=>
string(2) "B1"
["c_list"]=>
array(2) {
["1C1"]=>
array(3) {
["c_id"]=>
string(1) "1"
["c_name"]=>
string(2) "C1"
["d_list"]=>
NULL
}
["2C2"]=>
array(3) {
["c_id"]=>
string(1) "2"
["c_name"]=>
string(2) "C2"
["d_list"]=>
NULL
}
}
}
["2B2"]=>
array(3) {
["b_id"]=>
string(1) "2"
["b_name"]=>
string(2) "B2"
["c_list"]=>
array(1) {
["3C3"]=>
array(3) {
["c_id"]=>
string(1) "3"
["c_name"]=>
string(2) "C3"
["d_list"]=>
NULL
}
}
}
}
}
["2A2"]=>
array(3) {
["a_id"]=>
string(1) "2"
["a_name"]=>
string(2) "A2"
["b_list"]=>
array(1) {
["3B3"]=>
array(3) {
["b_id"]=>
string(1) "3"
["b_name"]=>
string(2) "B3"
["c_list"]=>
array(1) {
["4C4"]=>
array(3) {
["c_id"]=>
string(1) "4"
["c_name"]=>
string(2) "C4"
["d_list"]=>
&NULL
}
}
}
}
}
}
This is rather interesting. As far as I can tell, you are trying to transform a flat array into a multidimensional array, as well as transforming the keys into a multidimensional representation.
The top level difference seems to reside in the part before the underscore of the a_* keys.
Then, for each of these keys, every other *_ letters should induce it's own list.
This recursive function does the trick without hardcoding, will work with whatever number of levels, letters (or whatever else) and right identifiers.
It seems to return exactly the json you show in the sample ($array being the array as defined in your question)
$multidimension = multidimensionalify($array, ['a', 'b', 'c'], ['name']);
var_dump(json_encode($multidimension, JSON_PRETTY_PRINT));
function multidimensionalify(
array $input,
array $topLevelLetters,
array $rightHandIdentifiers,
$level = 0,
$parentId = null,
$uniqueString = 'id'
)
{
$thisDimension = [];
$thisLetter = $topLevelLetters[$level];
foreach ($input as $entry)
{
$thisId = $entry["{$thisLetter}_{$uniqueString}"];
$condition = true;
if ($parentId !== null)
{
$parentLetter = $topLevelLetters[$level - 1];
$condition = $entry["{$parentLetter}_{$uniqueString}"] === $parentId;
}
if (!isset($thisDimension[$thisId]) && $condition)
{
$thisObject = new stdClass;
$thisObject->{"{$thisLetter}_{$uniqueString}"} = $thisId;
foreach ($rightHandIdentifiers as $identifier)
{
$thisObject->{"{$thisLetter}_{$identifier}"} = $entry["{$thisLetter}_{$identifier}"];
}
if (isset($topLevelLetters[$level + 1])) {
$nextLetter = $topLevelLetters[$level + 1];
$thisObject->{"{$nextLetter}_list"} = multidimensionalify($input, $topLevelLetters, $rightHandIdentifiers, $level + 1, $thisId, $uniqueString);
}
$thisDimension[$thisId] = $thisObject;
}
}
return array_values($thisDimension);
}
Try this function just pass your array and key name for grouping and then convert to json.
public function _group_by($array, $key) {
$return = array();
foreach ($array as $val) {
$return[$val[$key]][] = $val;
}
return $return;
}
I'm retriving data from mysql. in my php I've got 2 arrays set
$main =array(); //tostore retrived data
$list =array('instock' => 'output1', 'item' => 'output2'); //existing key values and new key value to be replaced
How do I replace the keys with custom keys for each output? exmpale: custom keys output1,output2
current output
[{"instock":"yes", "item":"ch00024"},{..}]
Expected output
[{"output1":"yes", "output2":"ch00024"},{..}]
This is what I have tried so far. But does not work.
$main =array(); //tostore retrived data
$list =array('instock' => 'output1', 'item' => 'output2'); //replace key values
foreach ($result as $key => $value){
$main[ $list[ $key ] ] = $value;
}
echo json_encode( $main );
I get an error Undefined offset: 0. It points to this line $main[ $list[ $key ] ] = $value;
EDIT
This is a screen capture from my console
var_dump():
array(5) {
[0]=>
array(2) {
["instock"]=>
string(3) "yes"
["item"]=>
string(6) "it0215"
}
[1]=>
array(2) {
["instock"]=>
string(3) "yes"
["item"]=>
string(6) "it0381"
}
so on...
Your code works! The issue is in $list array you need define all keys in $result otherwise you need to check if there is that key in $list array.
$result =array(
'instock' => 'yes',
'item' => 'ch00024',
'color' => 'blue',
'price' => 100
);
$main = array();
$list = array('instock' => 'output1', 'item' => 'output2');
foreach ($result as $key => $value){
if (!empty($list[$key])) {
$main[$list[$key]] = $value;
}
}
echo json_encode($main);
Edit
Because you are access 2 dimensional array, so you need an extra loop to go through all items
$result = array(
array (
'instock' => 'yes',
'item' => 'it0215'
),
array(
'instock' => 'yes',
'item' => 'it0381'
)
);
$main = array();
$list = array('instock' => 'output1', 'item' => 'output2');
foreach ($result as $item){
foreach ($item as $key => $value) {
$main[$list[$key]] = $value;
}
}
echo json_encode($main);
The output is
{"output1":"yes","output2":"it0381"}
But In case you want to get all items with key replacement in new array. You should do something like this:
foreach ($result as $index => $item){
foreach ($item as $key => $value) {
$main[$index][$list[$key]] = $value;
}
}
echo json_encode($main);
The output is:
[
{"output1":"yes","output2":"it0215"},
{"output1":"yes","output2":"it0381"}
]
try to this code
$flippedList = array_flip($list);
I want to iterate over a multidimensional array, count the occurrences of a String inside and delete Array items where the count is higher than e.g. 3.
I've already tried a pretty messy combination of array_search, array_count_values and strpos inside a N^N loop, but this takes way to long to process and the results are wrong...
This is the Array, I'm trying to alter
array(2) {
[0]=>
array(13) {
["id"]=>
string(6) "1234"
["name"]=>
string(28) "aa"
["productcategory"]=>
string(30) "Branch1^^subbranch1"
["streamID"]=>
int(0)
["streamContext"]=>
string(16) "static"
["prio"]=>
string(3) "100"
}
[1]=>
array(11) {
["id"]=>
string(6) "9876"
["name"]=>
string(30) "bb"
["productcategory"]=>
string(66) "Branch1^^subbranch2"
["streamID"]=>
int(0)
["streamContext"]=>
string(16) "static"
["prio"]=>
string(3) "100"
}
}
The surrounding Array can have around 200 Items. I'm looking for a way to remove Items if theyr productcategory is found more than X times.
Can you guys help me with this?
Yeah I've had to deal with something kind of similar. If you're looking at an array of around 200, then it should be too slow to create a counter loop and then unset the values of the original array based on those counters. I've provided a template to think about, to see if this is the direction you're after.
It makes a copy of the array, then counts the productcategory, of course I'm assuming that category^^subcategory is the count you are looking for.
<?php
$your_array = array(
array(
array(
"id" => "1234",
"name" => "aa",
"productcategory" => "Branch1^^subbranch1",
"streamID" => '',
"streamContext" => "static",
"prio" => "100",
),
array(
"id" => "9876",
"name" => "bb",
"productcategory" => "Branch1^^subbranch1",
"streamID" => '',
"streamContext" => "static",
"prio" => "100",
),
array(
"id" => "9876",
"name" => "bb",
"productcategory" => "Branch1^^subbranch3",
"streamID" => '',
"streamContext" => "static",
"prio" => "100",
),
array(
"id" => "9876",
"name" => "bb",
"productcategory" => "Branch1^^subbranch2",
"streamID" => '',
"streamContext" => "static",
"prio" => "100",
),
array(
"id" => "9876",
"name" => "bb",
"productcategory" => "Branch1^^subbranch3",
"streamID" => '',
"streamContext" => "static",
"prio" => "100",
),
array(
"id" => "9876",
"name" => "bb",
"productcategory" => "Branch1^^subbranch1",
"streamID" => '',
"streamContext" => "static",
"prio" => "100",
),
),
);
$counters = array();
$limit = 1; // whatever the limit is that you want
foreach ($your_array as $index => $array) {
for ($i = 0; $i < count($array); $i++) {
if (!isSet($counters[$array[$i]['productcategory']])) {
$counters[$array[$i]['productcategory']] = 0;
}
$counters[$array[$i]['productcategory']]++;
if ($counters[$array[$i]['productcategory']] > $limit) {
unset($your_array[$index][$i]);
}
}
}
print '<pre>' . print_r($counters, true) . '</pre>';
print '<pre>' . print_r($your_array, true) . '</pre>';
I'm unsetting that item in the sub array, as I'm not sure if you want to just unset the whole item.
My first question for you would be "where is your data coming from?" If this is coming out of a database, then I would recommend you tweak your query there. You can definitely solve this in PHP, but as your data set grows it will take longer and longer to loop over the dataset in PHP.
To solve this in PHP, I would recommend you create a new "product index" array. This array would be associative with the product name as the keys and the values would contain an array of all the top-level indexes in your dataset array. Once you've built the index array, you can loop over that to find which product types occur more than 3 times in the main dataset and quickly delete those items.
$productIndex = [];
// Build an index of product categories
foreach($dataset as $i => $row) {
if (!is_array($productIndex[$row['productcategory']]) {
$productIndex[$row['productcategory']] = [];
}
$productIndex[$row['productcategory']][] = $i;
}
// Search for indexes with > 3 rows
foreach($productIndex as $items) {
if (count($items) > 3) {
// Delete said rows
foreach ($items as $index) {
unset($dataset[$index]);
}
}
}
I havent been able to use a one size fits it all approach, but for future reference i will share my "solution". It doesnt feel like super sophisiticated but it gets the job done...
function filter_categories($input, $count) {
$output = $input;
$exploded_input = [];
foreach ($output as $key => $value) {
$exploded_items = explode("^^", $value["productcategory"]);
array_push($exploded_input, $exploded_items);
}
$sortedbyCategory = [];
$last_items = [];
$counted_items = [];
foreach ($exploded_input as $key => $value) {
$end = end($value);
array_push($last_items, $end);
}
$counted = array_count_values($last_items);
foreach ($counted as $key => $value) {
if($value<=$count) {
unset($counted[$key]);
}
}
foreach ($counted as $k => $v) {
for ($i=0; $i < count($input); $i++) {
if(strpos($input[$i]["productcategory"], $k)){
if($counted[$k] > $count) {
$input[$i]["hide"] = true;
$counted[$k]--;
}
}
}
}
foreach ($input as $key => $value) {
if(isset($value["hide"])) {
unset($input[$key]);
}
}
return $input;
}