I have 2 arrays and i want to create an output array.
Example array requirements for Title and Subtitle field:
Array
(
[title] => Array
(
[required] => 1
[minLength] => 2
[maxLength] => 50
)
[subtitle] => Array
(
[required] => 1
[minLength] => 2
[maxLength] => 55
)
)
Post array after post s:
Array
(
[title] =>
[subtitle] => s
)
Example Output array:
Array
(
[title] => Array
(
[0] => this field is required
[1] => must be longer than 2
)
[subtitle] => Array
(
[0] => must be longer than 2
)
)
How can i generate such array by a foreach loop?
This is what i have, but it wont work well. If i leave title blank and subtitle 1 character he gives back 2 times this field is required. It looks like he duplicated.
class Forms_FormValidationFields {
private $_required;
private $_minLength;
private $_maxLength;
private $_alphaNumeric;
public $_errors;
public function __construct($validate, $posts) {
array_pop($posts);
$posts = array_slice($posts,1);
foreach ( $posts as $postName => $postValue) {
foreach( $validate[$postName] as $key => $ruleValue ){
$set = 'set'.ucfirst($key);
$get = 'get'.ucfirst($key);
$this->$set( $postValue , $ruleValue);
if( $this->$get() != '' || $this->$get() != NULL) {
$test[$postName][] .= $this->$get();
}
}
}
$this->_errors = $test;
}
public function setValidation(){
return $this->_errors;
}
public function getRequired() {
return $this->_required;
}
public function setRequired($value, $ruleValue) {
if (empty($value) && $ruleValue == TRUE) {
$this->_required = 'this field is required';
}
}
public function getMinLength() {
return $this->_minLength;
}
public function setMinLength($value, $ruleValue) {
if (strlen($value) < $ruleValue) {
$this->_minLength = ' must be longer than' . $ruleValue . '';
}
}
public function getMaxLength() {
return $this->_maxLength;
}
public function setMaxLength($value, $ruleValue) {
if (strlen($value) > $ruleValue) {
$this->_maxLength = 'must be shorter than' . $ruleValue . '';
}
}
}
Here you go:
<?php
$required = array(
'This field is not required',
'This field is required'
);
$length = 'Requires more than {less} but less than {more}';
$needs = array(
'title' => array(
'required' => 1,
'minLength' => 2,
'maxLength' => 50,
),
'subtitle' => array(
'required' => 1,
'minLength' => 2,
'maxLength' => 55
)
);
$new_needs = array();
foreach($needs as $key => $value) // Loop over your array
{
$new_needs[$key][] = $required[$value['required']];
$new_needs[$key][] = str_replace(
array('{more}', '{less}'),
array($value['maxLength'], $value['minLength']),
$length
);
}
foreach($_POST as $key => $value)
{
if(empty($value)) { echo $new_needs[$key][0]; }
if(strlen($value) > $needs[$key]['maxLength'] || strlen($value) < $needs[$key]['minLength']) echo $new_needs[$key][1];
}
Should be pretty self explanatory if you read over it.
Result:
Array
(
[title] => Array
(
[0] => This field is required
[1] => Requires more than 2 but less than 50
)
[subtitle] => Array
(
[0] => This field is required
[1] => Requires more than 2 but less than 55
)
)
Related
Goal: Generate an array that includes only those 'columns' with data, even though a 'header' may exist.
Example Data:
Array (
[HeaderRow] => Array (
[0] => Employee [1] => LaborHours [2] => 0.1 [3] => 0.25 [4] => 0.5 [5] => 0.8
)
[r0] => Array (
[0] => Joe [1] => 5 [2] => [3] => [4] => 50 [5] =>
)
[r1] => Array (
[0] => Fred [1] => 5 [2] => 10 [3] => [4] => [5] =>
)
)
Desired Output:
Array (
[HeaderRow] => Array (
[0] => Employee [1] => LaborHours [2] => 0.1 [4] => 0.5
)
[r0] => Array (
[0] => Joe [1] => 5 [2] => [4] => 50
)
[r1] => Array (
[0] => Fred [1] => 5 [2] => 10 [4] =>
)
)
So, in this very dumbed down example, the HeaderRow will always have data, but if both c0 and c1 are empty (as is the case for [3] and [5]) then I want to remove. I tried iterating through with for loops like I would in other languages, but that apparently doesn't work with associative arrays. I then tried doing a transpose followed by two foreach loops, but that failed me as well. Here's a sample of my for loop attempt:
Attempt with For Loop
for ($j = 0; $j <= count(reset($array))-1; $j++) {
$empty = true;
for ($i = 1; $i <= count($array)-1; $i++) {
if(!empty($array[$i][$j])) {
$empty = false;
break;
}
}
if ($empty === true)
{
for ($i = 0; $i <= count($array); $i++) {
unset($array[$i][$j]);
}
}
}
return $array;
Attempt with transpose:
$array = transpose($array);
foreach ($array as $row)
{
$empty = true;
foreach ($row as $value)
{
if (!empty($value))
{
$empty = false;
}
}
if ($empty) {
unset($array[$row]);
}
}
$array = transpose($array);
return $array;
function transpose($arr) {
$out = array();
foreach ($arr as $key => $subarr) {
foreach ($subarr as $subkey => $subvalue) {
$out[$subkey][$key] = $subvalue;
}
}
return $out;
}
I know the transpose one isn't terribly fleshed out, but I wanted to demonstrate the attempt.
Thanks for any insight.
We can make this more simpler. Just get all column values using array_column.
Use array_filter with a custom callback to remove all empty string values.
If after filtering, size of array is 0, then that key needs to be unset from all
subarrays.
Note: The arrow syntax in the callback is introduced since PHP 7.4.
Snippet:
<?php
$data = array (
'HeaderRow' => Array (
'0' => 'Employee','1' => 'LaborHours', '2' => 0.1, '3' => 0.25, '4' => 0.5, '5' => 0.8
),
'r0' => Array (
'0' => 'Joe', '1' => 5, '2' => '','3' => '', '4' => 50, '5' => ''
),
'r1' => Array (
'0' => 'Fred', '1' => 5,'2' => 10, '3' => '', '4' => '', '5' => ''
)
);
$cleanup_keys = [];
foreach(array_keys($data['HeaderRow']) as $column_key){
$column_values = array_column($data, $column_key);
array_shift($column_values); // removing header row value
$column_values = array_filter($column_values,fn($val) => strlen($val) != 0);
if(count($column_values) == 0) $cleanup_keys[] = $column_key;
}
foreach($data as &$row){
foreach($cleanup_keys as $ck){
unset($row[ $ck ]);
}
}
print_r($data);
It figures, I work on this for a day and have a moment of clarity right after posting. The answer was that I wasn't leveraging the Keys.:
function array_cleanup($array)
{
$array = transpose($array);
foreach ($array as $key => $value)
{
$empty = true;
foreach ($value as $subkey => $subvalue)
{
if ($subkey != "HeaderRow") {
if (!empty($subvalue))
{
$empty = false;
}
}
}
if ($empty) {
unset($array[$key]);
}
}
$array = transpose($array);
return $array;
}
I'm new in array. I wish to print out the values of all possible [type] [label] [value]. I wish to do like "if there's a type with select, then display all labels with values"
Below is my array.
Array
(
[product_id] => 8928
[title] => Example of a Product
[groups] => Array
(
[8929] => Array
(
[8932] => Array
(
[type] => select
[label] => Section
[id] => pewc_group_8929_8932
[group_id] => 8929
[field_id] => 8932
[value] => Section 200
[flat_rate] => Array
(
)
)
)
)
[price_with_extras] => 0
[products] => Array
(
[field_id] => pewc_group_8929_9028
[child_products] => Array
(
[8945] => Array
(
[child_product_id] => Array
(
[0] => 8945
)
[field_id] => pewc_group_8929_9028
[quantities] => one-only
[allow_none] => 0
)
)
[pewc_parent_product] => 8928
[parent_field_id] => pewc_5d678156d81c6
)
)
The site is saying "
It looks like your post is mostly code; please add some more details." So here's my so-called lorem ipsum :D
You can use array_walk_recursive for the same,
array_walk_recursive($arr, function ($value, $key) {
// check if key matches with type, label or value
if (count(array_intersect([$key], ['type', 'label', 'value'])) > 0) {
echo "[$value] ";
}
});
Demo
Output
[select] [Section] [Section 200]
EDIT
You can modify the condition as,
if($key === 'type' && $value == 'select')
EDIT 1
array_walk_recursive($arr, function ($value, $key) {
if($key === 'type' && $value == 'select'){
echo "[$value] ";
}
});
EDIT 2
function search_by_key_value($arr, $key, $value)
{
$result = [];
if (is_array($arr)) {
if (isset($arr[$key]) && $arr[$key] == $value) {
$result[] = $arr;
}
foreach ($arr as $value1) {
$result = array_merge($result, search_by_key_value($value1, $key, $value));
}
}
return $result;
}
// find array by key = type and value = select
$temp = search_by_key_value($arr, 'type', 'select');
$temp = array_shift($temp);
print_r($temp);
echo $temp['label'];
echo $temp['value'];
Demo
I have an array storing all subcategories of root category, for example:
I just want to list them like this:
A
A>B
A>B>C
A>B>C>E
A>B>D
A>B>D>F
A>B>G
A>B>G>H
My array:
Array (
[0] => Array (
[id] => 2
[title] => B
[sub_category] => Array (
[0] => Array (
[id] => 3
[title] => C
[sub_category] => Array (
[0] => Array (
[id] => 5
[title] => E
[sub_category] => Array ()
)
)
)
[1] => Array (
[id] => 4
[title] => D
[sub_category] => Array (
[0] => Array (
[id] => 6
[title] => F
[sub_category] => Array ()
)
)
)
[2] => Array (
[id] => 7
[title] => G
[sub_category] => Array (
[0] => Array (
[id] => 10
[title] => H
[sub_category] => Array ()
)
)
)
)
)
)
My functions are listing them with no '>' and with no parents, just title.
Here are my functions:
function buildTree($tree) {
foreach ($tree as $node)
{
echo '<li>'.$node['title'].'</li>';
if (!empty($node['sub_category'])) {
echo '<ul>';
buildTree($node['sub_category']);
echo '</ul>';
}
}
}
function categoryTree($db, $root_id) {
$tree = array();
$sub_categories = $db->get_results('SELECT * FROM categories WHERE parentid="'.$root_id.'"');
if ($sub_categories) {
foreach ($sub_categories as $sub_category) {
$tree[] = array(
"id" => $sub_category->id,
"title" => $sub_category->title,
"sub_category" => categoryTree($db, $sub_category->id)
);
}
}
return $tree;
}
It's solved. Here is my new code:
function buildTree($db, $tree) {
foreach ($tree as $node)
{
$header = array();
$id = $node['id'];
$can_i_stop = false;
$has_parent = $db->get_var('SELECT parentid FROM categories WHERE id="'.$node['id'].'"');
if (!($has_parent == '') && !($has_parent == null)) {
$seperator = ' > ';
}else{
$seperator = '';
}
while ($can_i_stop == false) {
$parent_id = $db->get_var('SELECT parentid FROM categories WHERE id="'.$id.'"');
if (!($parent_id == '') && !($parent_id == null)) {
$parent_title = $db->get_var('SELECT title FROM categories WHERE id="'.$parent_id.'"');
array_push($header, $parent_title);
$id = $parent_id;
$can_i_stop = false;
}else{
$can_i_stop = true;
}
}
echo '<li>'.implode(' > ', array_reverse($header)).$seperator.$node['title'].'</li>';
if (!empty($node['sub_category'])) {
echo '<ul>';
buildTree($db, $node['sub_category']);
echo '</ul>';
}
}
}
function categorySubTree($db, $root_id) {
$tree = array();
$sub_categories = $db->get_results('SELECT * FROM categories WHERE parentid="'.$root_id.'"');
if ($sub_categories) {
foreach ($sub_categories as $sub_category) {
$tree[] = array(
"id" => $sub_category->id,
"title" => $sub_category->title,
"sub_category" => categorySubTree($db, $sub_category->id)
);
}
}
return $tree;
}
function categoriesTree($db) {
$tree = array();
$categories = $db->get_results('SELECT * FROM categories WHERE is_subcategory=0');
if ($categories) {
foreach ($categories as $category) {
$tree[] = array(
"id" => $category->id,
"title" => $category->title,
"sub_category" => categorySubTree($db, $category->id)
);
}
}
return $tree;
}
I have a large multidimensional array something like the below:
Array(
[1] => Array ( [type] => blah1 [category] => cat1 [exp_range] => this_week )
[2] => Array ( [type] => blah1 [category] => cat2 [exp_range] => next week )
[3] => Array ( [type] => blah1 [category] => cat1 [exp_range] => next week )
[4] => Array ( [type] => blah2 [category] => cat2 [exp_range] => this_week )
)
I want to be able to filter this array with multiple filters.
eg. filtering where category = cat1 and type = blah1 would return array 1 and 3.
I have the below function that would return keys 1,2,3 which is incorrect as array 2 doesnt have both cat1 and blah1
Can anyone see what I need to do to get this working?
Also would it be possible to incorporate sortin in this function, if so how?
function array_searcher($needles, $array) {
foreach ($needles as $needle) {
foreach ($array as $key => $value) {
foreach ($value as $v) {
if ($v == $needle) {
$keys[] = $key;
}
}
}
}
return $keys;
}
I decided to rewrite my answer to accommodate both filtering and sorting. I took a heavily object oriented approach to solving this problem, which I will detail below.
You can see all of this code in action at this ideone.com live demonstration.
The first thing I did was define two interfaces.
interface Filter {
public function filter($item);
}
interface Comparator {
public function compare($a, $b);
}
As their names suggest, Filter is used for filtering, and Comparator is used for comparing.
Next, I defined three concrete classes that implements these interfaces, and accomplish what I wanted.
First is KeyComparator. This class simply compares the key of one element to the key of another element.
class KeyComparator implements Comparator {
protected $direction;
protected $transform;
protected $key;
public function __construct($key, $direction = SortDirection::Ascending, $transform = null) {
$this->key = $key;
$this->direction = $direction;
$this->transform = $transform;
}
public function compare($a, $b) {
$a = $a[$this->key];
$b = $b[$this->key];
if ($this->transform) {
$a = $this->transform($a);
$b = $this->transform($b);
}
return $a === $b ? 0 : (($a > $b ? 1 : -1) * $this->direction);
}
}
You can specify a sort direction, as well as a transformation to be done to each element before they are compared. I defined a helped class to encapsulate my SortDirection values.
class SortDirection {
const Ascending = 1;
const Descending = -1;
}
Next, I defined MultipleKeyComparator which takes multiple KeyComparator instances, and uses them to compare two arrays against each other. The order in which they are added to the MultipleKeyComparator is the order of precedence.
class MultipleKeyComparator implements Comparator {
protected $keys;
public function __construct($keys) {
$this->keys = $keys;
}
public function compare($a, $b) {
$result = 0;
foreach ($this->keys as $comparator) {
if ($comparator instanceof KeyComparator) {
$result = $comparator->compare($a, $b);
if ($result !== 0) return $result;
}
}
return $result;
}
}
Finally, I created MultipleKeyValueFilter which is meant to filter an array based on an array of key/value pairs:
class MultipleKeyValueFilter implements Filter {
protected $kvPairs;
public function __construct($kvPairs) {
$this->kvPairs = $kvPairs;
}
public function filter($item) {
$result = true;
foreach ($this->kvPairs as $key => $value) {
if ($item[$key] !== $value)
$result &= false;
}
return $result;
}
}
Now, given the input array (Notice I rearranged them a bit to make the sorting obvious):
$array = array (
'1' => array ('type' => 'blah2', 'category' => 'cat2', 'exp_range' => 'this_week' ),
'2' => array ('type' => 'blah1', 'category' => 'cat1', 'exp_range' => 'this_week' ),
'3' => array ('type' => 'blah1', 'category' => 'cat2', 'exp_range' => 'next_week' ),
'4' => array ('type' => 'blah1', 'category' => 'cat1', 'exp_range' => 'next_week' )
);
Sorting can be achieved by doing the following:
$comparator = new MultipleKeyComparator(array(
new KeyComparator('type'),
new KeyComparator('exp_range')
));
usort($array, array($comparator, 'compare'));
echo "Sorted by multiple fields\n";
print_r($array);
Filtering can be achieved by doing the following:
$filter = new MultipleKeyValueFilter(array(
'type' => 'blah1'
));
echo "Filtered by multiple fields\n";
print_r(array_filter($array, array($filter, 'filter')));
At this point I've given you a great deal of code. I'd suggest that your next step is to combine these two pieces into a single class. This single class would then apply both filtering and sorting together.
Do it:
$arr = array(
1 => array ( "type" => "blah1", "category" => "cat1", "exp_range" => "this_week" ),
2 => array ( "type" => "blah1", "category" => "cat2", "exp_range" => "next week" ),
3 => array ( "type" => "blah1", "category" => "cat1", "exp_range" => "this_week" ),
4 => array ( "type" => "blah2", "category" => "cat2","exp_range" => "next week" ),
);
function filter(array $arr,array $params){
$out = array();
foreach($arr as $key=>$item){
$diff = array_diff_assoc($item,$params);
if (count($diff)==1) // if count diff == 1 - Ok
$out[$key] = $item;
}
return $out;
}
$out = filter($arr,array("type" => "blah1", "category" => "cat1"));
echo '<pre>';
print_r($out);
echo '</pre>';
// output
Array
(
[1] => Array
(
[type] => blah1
[category] => cat1
[exp_range] => this_week
)
[3] => Array
(
[type] => blah1
[category] => cat1
[exp_range] => this_week
)
)
The issue is the fact that your function will return the key of every array that contains "cat1" or "blah1". You can fix it with array_unique():
function array_searcher($needles, $array) {
foreach ($needles as $needle) {
foreach ($array as $key => $value) {
foreach ($value as $v) {
if ($v == $needle) {
$keys[] = $key;
}
}
}
}
return $keys;
}
$bigarray = array(
array('type' => 'blah1', 'category' => 'cat1', 'exp_range' => 'this_week'),
array('type' => 'blah1', 'category' => 'cat2', 'exp_range' => 'next week'),
array('type' => 'blah1', 'category' => 'cat1', 'exp_range' => 'next week'),
array('type' => 'blah2', 'category' => 'cat2', 'exp_range' => 'this_week')
);
$result = array_searcher(array('cat1','blah1'), $bigarray);
$unique_result = array_unique($result);
print_r($unique_result);
so lets assign your base array to a variable:
$array = Array(
[1] => Array ( [type] => blah1 [category] => cat1 [exp_range] => this_week )
[2] => Array ( [type] => blah1 [category] => cat2 [exp_range] => next week )
[3] => Array ( [type] => blah1 [category] => cat1 [exp_range] => next week )
[4] => Array ( [type] => blah2 [category] => cat2 [exp_range] => this_week )
)
and lets's have an array containing our filter:
$filter = array(
'type' => 'blah1'
'category' => 'cat1'
)
then we start our filtering script
foreach ($array as $key => $row){
$i = 0;
foreach ($filter as $filterKey => $filterValue){
if ($row[$filterKey] != $filterValue){
$i++;
}}
if ($i == 0){
$filteredArray[] = $row;
}}
if $i still equals 0 after the row is tested against our filter, we add the row to our filtered array
I vaguely remember implementing this type of functionality many years ago:
http://forums.devnetwork.net/viewtopic.php?t=47855
Look to the sortRows() and _quickSort() methods
HTH
How can I turn the first array in to the second one? The goal is to create an array that shows the hierarchy, based on location_id and parent_id. Each location_name should be in an array of which the key is its parent_id.
Ignore the values I gave to location_name. No value for parent_id == NULL, these are the top level items.
First array:
Array
(
[0] => stdClass Object
(
[location_id] => 1
[location_name] => Town 1
[parent_id] =>
)
[1] => stdClass Object
(
[location_id] => 2
[location_name] => Town 1.1
[parent_id] =>
)
[2] => stdClass Object
(
[location_id] => 3
[location_name] => Town 1.2
[parent_id] => 1
)
[3] => stdClass Object
(
[location_id] => 4
[location_name] => Town 1.3
[parent_id] => 1
)
[4] => stdClass Object
(
[location_id] => 5
[location_name] => town 1.1.1
[parent_id] => 2
)
[5] => stdClass Object
(
[location_id] => 6
[location_name] => Town 1.1.2
[parent_id] => 3
)
);
Resulting array should be:
Array(
'Town 1' = array(
'town 1.2',
'town 1.3' = array(
'town 1.1.2'
)
),
'Town 2' = array(
'town 1.1.1'
)
);
EDIT: working solution based on Rijk's answer
function _order_locs($parent, $array)
{
$return = array();
foreach ( $array as $town )
{
if ( $town->parent_id == $parent )
{
$set = $this->_order_locs( $town->location_id, $array );
if( $this->_menu_is_parent($town->location_id, $array) ) $return[$town->location_name] = $set;
else $return[] = $town->location_name;
}
}
return $return;
}
function _menu_is_parent($id, $array)
{
foreach( $array as $a )
{
if( $a->parent_id == $id ) return TRUE;
}
}
You have to loop through it, using a recursive function (one that calls itself):
function getChilds( $parent, $array ) {
$return = array();
foreach ( $array as $town ) {
if ( $town['location_id'] == $parent ) {
$return[] = array(
'name' => $town['location_name'],
'childs' => getChilds( $town['location_id'], $array )
);
}
}
return $return;
}
$towns_tree = getChilds( 0, $towns );
Might not work right off the bat, but that gives you a nice oppurtunity to play with the code and get familiar with this concept ;)
Here is some code that will more or less do what you need. You will have to tweak it to your liking.
<?php
Class Node {
public $id;
public $parent_id;
public $value;
public $children;
public $depth;
function __construct($id, $parent_id, $value) {
$this->id = $id;
$this->parent_id = $parent_id;
$this->value = $value;
$this->children = array();
$this->depth = 0;
}
function add_child(Node $new_child) {
if ($new_child->parent_id == $this->id) {
$this->children[$new_child->id] = $new_child;
$this->children[$new_child->id]->depth = $this->depth + 1;
} else {
foreach ($this->children as $child) {
$child->add_child($new_child);
}
}
}
function to_array() {
if (count($this->children) > 0) {
$arr = array();
foreach ($this->children as $child) {
array_push($arr, $child->to_array());
}
return array($this->value => $arr);
} else {
return $this->value;
}
}
function str() {
echo str_repeat(" ", $this->depth) . $this->value . "\n";
foreach ($this->children as $child) {
$child->str();
}
}
}
?>
Here is some sample code to test it with:
<?php
$arr = Array(
array('location_id' => 1,
'location_name' => 'Town 1',
'parent_id' => 0),
array('location_id' => 2,
'location_name' => 'Town 1.1',
'parent_id' => 0),
array('location_id' => 3,
'location_name' => 'Town 1.2',
'parent_id' => 1),
array('location_id' => 4,
'location_name' => 'Town 1.3',
'parent_id' => 1),
array('location_id' => 5,
'location_name' => 'Town 1.1.1',
'parent_id' => 2),
array('location_id' => 6,
'location_name' => 'Town 1.1.2',
'parent_id' => 3)
);
$root = new Node(0, 0, 'root');
foreach ($arr as $item) {
$node = new Node($item['location_id'],
$item['parent_id'],
$item['location_name']);
$root->add_child($node);
}
$tree = $root->to_array();
$tree = $tree['root'];
var_dump($tree);
?>