I registered two query varaible 'star' & 'cord'
And when I visit https://website.com/blog/star-4-5/cord-Corded/
and use $star = explode( '-', get_query_var('star', '') );
$star output is shows as
Array ( [0] => 4 [1] => 5/cord [2] => Corded )
and $cord output is shows as 'Empty'
While $star should show Array ( [0] => 4 [1] => 5 )
and $cord should show 'Corded '
function trimmer_register_query_vars( $vars ) {
$vars[] = 'brand';
$vars[] = 'price';
$vars[] = 'water';
$vars[] = 'star';
$vars[] = 'cord';
return $vars;}add_filter( 'query_vars', 'trimmer_register_query_vars' );
Here's written rule I used for it, it automatically rewrite a combination of all queries.
function generate_rewrite_rules($keys) {
$total_keys = count($keys);
$rules = array();
for ($i = 1; $i <= $total_keys; $i++) {
$combinations = combinations($keys, $i);
foreach ($combinations as $combination) {
$rule = '^trimmer/';
$query = 'index.php?post_type=trimmer&';
$j = 1;
foreach ($combination as $key) {
$rule .= $key . '-(.+?)/'; // Use non-greedy match (`.+?`) instead of greedy match (`.+`)
$query .= $key . '=$matches[' . $j . ']&';
$j++;
}
$rule = rtrim($rule, '/');
$rule .= '/?$';
$query = rtrim($query, '&');
$rules[] = array(
'rule' => $rule,
'query' => $query,
'top' => true
);
}
}
return $rules;
}
function combinations($keys, $length) {
if ($length == 1) {
return array_map(function($val) {
return array($val);
}, $keys);
}
$result = array();
for ($i = 0; $i < count($keys) - $length + 1; $i++) {
$head = $keys[$i];
$combos = combinations(array_slice($keys, $i + 1), $length - 1);
foreach ($combos as $combo) {
array_unshift($combo, $head);
$result[] = $combo;
}
}
return $result;
}
add_action('init', 'register_trimmer_rules');
function register_trimmer_rules() {
$keys = array('brand', 'price', 'cord', 'water', 'star');
$rules = generate_rewrite_rules($keys);
foreach ($rules as $rule) {
add_rewrite_rule($rule['rule'], $rule['query'], $rule['top']);
}
}
Related
I'm inserting multiple data in table through loop on 2D array.
This is my data:
$data['id'] = array([0] => '1', [1] => '2');
$data['name'] = array([0] => 'Ben', [1] => 'Dan');
$data['status'] = array([0] => 'Active', [1] => 'Active');
$data['updatedby'] = '1';
$data['updateddate'] = date('d-M-y H:i');
$idColumn = 'id';
$table = 'tablename';
This is my code:
foreach($data as $key => $value){
$i = 0;
if($key <> 'updatedby' && $key <> 'updateddate'){
foreach($value as $row){
$result = $this->myModel->recordUpdate($idColumn, $data['id'][$i], array($key => $row), $table);
$i = $i + 1;
}
}
if($key == 'updatedby'){
foreach($data['id'] as $row){
$result = $this->myModel->recordUpdate($idColumn, $row, array($key => $data['updatedby']), $table);
}
}
if($key == 'updateddate'){
foreach($data['id'] as $row){
$result = $this->myModel->recordUpdate($idColumn, $row, array($key => $data['updateddate']), $table);
}
}
}
function recordUpdate($idColumn, $id, $data, $table)
{
$this->db->where($idColumn, $id);
$this->db->update($table, $data);
$update_id = $this->db->affected_rows();
return $update_id;
}
Is there any way to do main loop through rows first then column, I would like to make this code more shorter and reliable.
You can do it by filtering and transposing your main data first:
$rows = array_transpose(array_filter($data, function($key){
return !in_array($key, ["updatedby","updateddate"]);
}, ARRAY_FILTER_USE_KEY));
function array_transpose($array){
$keys = array_keys($array);
$new_array = [];
for($i = 0, $len = count($array[$keys[0]]); $i < $len; $i++){
$new_array[$i] = [];
foreach($keys as $key){
$new_array[$i][$key] = $array[$key][$i];
}
}
return $new_array;
}
Then you can loop over the rows like this:
for($row = 0, $cnt = count($rows); $row < $cnt; $row++){
$column_data = $rows[$row];
$column_keys = array_keys($column_data);
$column_id = $column_data[$idColumn];
foreach($column_keys as $key){
recordUpdate(
$idColumn,
$column_id,
[$key => $column_data[$key]],
$table
);
}
// set the updatedby and updateddate for each row
$this->myModel->recordUpdate($idColumn, $column_id, ["updatedby" => $data["updatedby"]], $table);
$this->myModel->recordUpdate($idColumn, $column_id, ["updateddate" => $data["updateddate"]], $table);
}
I have an array which contains 3 different arrays.
$arrayAll = (
0 => $array1,
1 => $array2,
2 => $array3
);
How can I loop through $arrayAll, displaying the first element of each sub-array(array1,array2,array3) on each itteration?
So, the output will be:
$array1[0],$array2[0],$array3[0],
$array1[1],$array2[1],$array3[1],
$array1[2],$array2[2],$array3[2]
and so on.. until all sublements are fetched.
EDIT:
$addsContent = $Adds->selectAdds(10);
$sharedArticlesContent = $SharedContent->getSharedContent($topic_selected, $filter_selected);
$blogPostsContent = $BlogPosts->getRecentBlogPostsByTopic("business");
$contentArray = array(
$sharedArticlesContent,
$addsContent ,
$blogPostsContent
);
foreach($contentArray as $value)
{
if(count($value)>$maxLength)
{
$maxLength = count($value);
}
}
for($i=0; $i<$maxLength; $i++)
{
foreach($contentArray as $value)
{
if(isset($value[$i]))
{
if($value==$sharedArticlesContent){
$data = $value[$i];
foreach($sharedArticlesContent as $data){
$post_id = $data['id'];
$uploaded_by = $data['uploaded_by'];
$text = $data['text'];
$image = $data['image'];
require 'template1.php';
}
}elseif($value==$addsContent){
//template2
}else{
//template3
}
}
}
}
$maxLength = 0;
foreach($arrayAll as $value)
{
if(count($value)>$maxLength)
{
$maxLength = count($value);
}
}
for($i=0; $i<$maxLength; $i++)
{
foreach($arrayAll as $value)
{
if(isset($value[$i]))
{
echo $value[$i];
}
}
}
I'm trying to solve a somewhat simple task but can't wrap my head around doing it without a lot of loops and messy code.
I want all to print all combinations of the array below:
$product = array(
array
(
'1X'
),
array
(
'X2'
)
);
producing the following result:
//ROW 1
1
X
//ROW 2
X
2
//ROW 3
1
2
//ROW 4
X
X
this work:
$product = array(
array
(
'1WQ'
),
array
(
'3'
),
array
(
'X'
)
);
//
class Combine{
private $product = array();
private $result = array();
private $format = array();
public function __construct($p=array()){
$this->product = $p;
}
public function process(){
foreach($this->product as $k=>$v){
$this->format[] = str_split($v[0]);
}
$this->result = $this->build();
return $this;
}
public function build()
{
if (!$this->format) {
return array(array());
}
$sub = array_shift($this->format);
$c = $this->build($this->format);
$res = array();
foreach ($sub as $v) {
foreach ($c as $p) {
array_unshift($p, $v);
$res[] = $p;
}
}
return $res;
}
public function response(){
return $this->result;
}
}
//
$combine = new Combine($product);
$resp = $combine->process()->response();
var_dump($resp);
function helperFunction($array, $index, $workArray)
{
$tempArray = array();
$tmpStr = $array[$index][0];
// loop over the current array characters
for( $i = 0; $i < strlen($tmpStr); $i++ )
{
$char = substr($tmpStr, $i, 1);
// first time - add characters to the work array
if (count($workArray) == 0)
{
$tempArray[] = $char;
}
// later round - add characters to existing items
else
{
foreach ($workArray as $workItem)
{
$tempArray[] = $workItem . $char;
}
}
}
// last round
if (count($array) == $index + 1)
{
return $tempArray;
}
// recursion round
else
{
return helperFunction($array, $index + 1, $tempArray);
}
}
$result = helperFunction($product, 0, array());
I have a loop which increments the limit of the content which is showing on a website (json content).
The problem is that the loop stops at 50. The links that are generated with the incrementation are working fine when I'm calling them in the browser. The content is shown.
But I store only the content of the first 50 and then it stops.
public static function getAllCustomers() {
$rest = Rest::getInstance();
$spaces = self::getSpaces();
$customers = array();
$path = SpacePath::buildPath();
for ($i = 0;
; $i += Paths::$MAX_CONTENT_LENGTH) {
$temp = $path . '?start=' . $i . '&limit=50';
$content = Helper::toArray($temp);
print_r($temp);
// print_r(empty($content['results']));
if (!empty($content['results'])) {
foreach ($content ['results'] as $space) {
if (!preg_match('|^(.*?)-([0-9]+)|i', $space ['name'], $matches)) {
continue;
}
$customer = (object) array(
'name' => $matches [0],
'ident' => $matches [1],
'id' => $matches [2],
'space_key' => $space ['key'],
'options' => array()
);
$customers [] = $customer;
}
break;
}
}
print_r($customers);
return $customers;
}
Here, let me reformat your code so you can see what relates to what...
public static function getAllCustomers()
{
$rest = Rest::getInstance();
$spaces = self::getSpaces();
$customers = array();
$path = SpacePath::buildPath();
for ($i = 0; ; $i += Paths::$MAX_CONTENT_LENGTH)
{
$temp = $path . '?start=' . $i . '&limit=50';
$content = Helper::toArray($temp);
print_r($temp);
//print_r(empty($content['results']));
if (!empty($content['results']))
{
foreach ($content ['results'] as $space)
{
if (!preg_match('|^(.*?)-([0-9]+)|i', $space ['name'], $matches))
{
continue;
}
$customer = (object) array('name' => $matches [0]
,'ident' => $matches [1]
,'id' => $matches [2]
,'space_key' => $space ['key']
,'options' => array()
);
$customers [] = $customer;
}
break; // oops
}
}
print_r($customers);
return $customers;
}
You'll notice I added a comment to your break statement. ;)
I need to get all the combinations and permutations of an array of array of values. See snippet for example:
$a = array(
1,
2
);
$b = array(
'foo',
'bar'
);
$params = array();
$params[] = $a;
$params[] = $b;
// What to do to $params so I can get the following combinations/permutations?
// 1,foo
// 2,foo
// 1,bar
// 2,bar
// foo,1
// bar,1
// foo,2
// bar,2
Keep in mind that the $params can be any size and the items in it can also be any size.
function all($array, $partial, &$result) {
if ($array == array()) {
$result[] = implode(',', $partial);
return;
}
for($i=0; $i<count($array);$i++) {
$e = $array[$i];
$a = $array;
array_splice($a, $i, 1);
foreach($e as $v) {
$p = $partial;
$p[] = $v;
all($a, $p, $result);
}
}
}
Test:
$a = array(1, 2, 3);
$b = array('foo', 'bar');
$c = array('a', 'b');
$params = array($a, $b, $c);
$result = array();
all($params, array(), $result);
print_r($result);
Note: if there is a chance for duplicates (arrays contain the same values) you can check for duplicates before inserting into the $result.
Here is my solution. It should work with any number of associative arrays, even if they contained nested associative arrays.
<?php
$a = array(1,2,3);
$b = array('foo','bar','baz', array('other','other2',array('other3','other4')));
$params = array();
$params[] = $a;
$params[] = $b;
$elements = array();
foreach($params as $param) {
addElement($param,$elements);
}
function addElement($arg,&$result) {
if(!is_array($arg)) {
$result[] = $arg;
} else {
foreach($arg as $argArray) {
addElement($argArray,$result);
}
}
}
for($i=0; $i<count($elements); $i++) {
$curElement = $elements[$i];
for($j=0; $j<count($elements); $j++) {
if($elements[$j] != $curElement) {
$final_results[] = $curElement.','.$elements[$j];
}
}
}
print_r($final_results);
?>
http://codepad.viper-7.com/XEAKFM
Here's a possible solution codepad...
$array = array(
0 => array(
'foo',
'bar'
),
1 => array(
1,
2,
3
),
2 => array(
'x',
'y',
'z'
),
3 => array(
7,
8,
9
)
);
array_permutations($array, $permutations);
print_r($permutations);
public function array_permutations($array, &$permutations, $current_key = 0, $current_subkey = 0)
{
if(!isset($array[$current_key][$current_subkey]))
{
return;
}
$current_val = $array[$current_key][$current_subkey];
foreach($array as $array_key => $row)
{
foreach($row as $row_key => $sub_val)
{
if($array_key === $current_key)
{
if($row_key !== $current_subkey)
{
$permutations[] = $current_val . ', ' . $sub_val;
}
}
else
{
$permutations[] = $current_val . ', ' . $sub_val;
}
}
}
$next_key = ($current_subkey == (count($array[$current_key]) - 1)) ? $current_key + 1 : $current_key;
$next_subkey = ($next_key > $current_key) ? 0 : $current_subkey + 1;
array_permutations($array, $permutations, $next_key, $next_subkey);
}
Try this out, hope this helps
$a = array(
1,
2,
4
);
$b = array(
'foo',
'bar',
'zer'
);
$c = array(
'aaa',
'bbb'
);
$params = array();
$params[] = $a;
$params[] = $b;
$params[] = $c;
$sizeofp = count($params);
for($i=0 ; $i < $sizeofp ; $i++){
foreach ($params[$i] as $paramA) {
for($j=0 ; $j < $sizeofp ; $j++){
if($j == $i){
continue;
}
foreach($params[$j] as $paramB){
echo "\n".$paramA.",".$paramB;
}
}
}
}