Insert php variable inside array - php

I have a filter for the CPT and I need to manually type all custom taxonomy names inside the array():
sc_render_filter(
'test',
'All Categories',
array( 'Category One', 'Category two', 'Category three'),
''
. ($current_sub_brand ? ( 'sub_brand=' . $current_sub_brand . '&' ) : '' )
. ($current_varietal ? ( 'varietal=' . $current_varietal . '&' ) : '' )
. ($current_publication ? ( 'publication=' . $current_publication . '&' ) : '' )
. ($current_vintage ? ( 'vintage=' . $current_vintage . '&' ) : '' )
);
Is it possible somehow to use the variable or foreach loop inside array() to automatically generate terms or names? Or maybe I need another approach?
This is what I have in foreach:
$source = '';
foreach ($termslist as $term) {
$source .= "'". $term->name. "'". ',';
}
echo rtrim($source, ',');

Unfortuntely for your project, it is appropriate to use variable variables (which I do not typically endorse). Using variable variables is a symptom that array data is not properly stored as such. The fact that you have individual $current_ variables looks to be an earlier problem to address.
In the meantime, you can loop through the know keys and dynamically access these variables. When finished, call http_build_query() to cleanly, reliably generate a url querystring string.
Code: (Demo)
$keys = ['sub_brand', 'varietal', 'publication', 'vintage'];
$data = [];
foreach ($keys as $key) {
$data[$key] = ${'current_' . $key};
}
$queryString = http_build_query($data);
sc_render_filter(
'test',
'All Categories',
['Category One', 'Category two', 'Category three'],
$queryString
);
The querystring string looks like this:
sub_brand=foo&varietal=bar&publication=boo&vintage=far

Related

Convert PHP array into HTML tag attributes separated by spaces

I need to convert a PHP array into HTML tag attributes, with spaces and quotes, this is an example:
$array=array(
'attr1'=>'value1',
'id'=>'example',
'name'=>'john',
'class'=>'normal'
);
This is the result I need to achieve:
attr1="value1" id="example" name="john" class="normal"
There is any PHP function to do it?
I am trying these:
http_build_query
array_walk
You can also use this easy one line code, please follwo below code::
$array=array(
'attr1'=>'value1',
'id'=>'example',
'name'=>'john',
'class'=>'normal'
);
$data = str_replace("=", '="', http_build_query($array, null, '" ', PHP_QUERY_RFC3986)).'"';
echo $data;
Output
attr1="value1" id="example" name="john" class="normal"
I use the following function:
function buildAttributes($attributes)
{
if (empty($attributes))
return '';
if (!is_array($attributes))
return $attributes;
$attributePairs = [];
foreach ($attributes as $key => $val)
{
if (is_int($key))
$attributePairs[] = $val;
else
{
$val = htmlspecialchars($val, ENT_QUOTES);
$attributePairs[] = "{$key}=\"{$val}\"";
}
}
return join(' ', $attributePairs);
}
It correctly escapes special html characters and supports boolean attributes (attributes without value). The following input:
[
'name' => 'firstname',
'value' => 'My Name',
'required'
]
Will produce:
name="firstname" value="My Name" required
Use a foreach loop to get the value and key.
$array = array(
'attr1'=>'value1',
'id'=>'example',
'name'=>'john',
'class'=>'normal');
foreach ($array as $key => $value) {
echo $key . '="' . htmlspecialchars($value) . '" ';
}
If you wanted to use a function, you could just make your own such as the following.
$array = array(
'attr1'=>'value1',
'id'=>'example',
'name'=>'john',
'class'=>'normal');
echo buildTag($array);
function buildTag ($array) {
$tag = '';
foreach ($array as $key => $value) {
$tag .= $key . '="' . htmlspecialchars($value) . '" ';
}
return $tag;
}
You could also utilize array_map() in conjunction with array_keys() to build your $key=$value string.
Wrapped in array_filter() to remove empty items and ultimately use implode() to glue your items together.
$array = array(
'attr1' => 'value1',
'id' => 'example',
'name' => 'john',
'class' => 'normal',
'c' => null,
'd' => '',
'e' => '"abc"'
);
$attributes = implode( ' ', array_filter( array_map( function ( $key, $value ) {
return $value ? $key . '="' . htmlspecialchars( $value ) . '"' : false;
}, array_keys( $array ), $array ) ) );
echo "<div " . $attributes . "></div>";
Result:
<div attr1="value1" id="example" name="john" class="normal" e=""abc""></div>
The shortest one-line function to do that would be:
function add_attributes($attributes){
return urldecode(http_build_query(array_map(function($v){ return '"'.((string) $v).'"'; }, $attributes), '', ' '));
}
You can use it like this:
$array=array(
'attr1'=>'value1',
'id'=>'example',
'name'=>'john',
'class'=>'normal'
);
echo '<div '.add_attributes($array).'></div>';
will produce:
<div attr1="value1" id="example" name="john" class="normal"></div>
You can use this function:
public static function arrayToStringTags( $array )
{
$tags = '';
if(!(is_array($array) && !empty($array)))
{
return $tags;
}
foreach($array as $key => $value)
{
$tags .= $key. '="'. $value. '" ';
}
return $tags;
}

change array values during foreach. Adding html element to every array item

I wanted to ask, how can i modify array values when doing foreach - in my example, i want to add to every element, but this code produces error.
foreach ($logo as &$value) {
$value = '<div>' . $value . '</div>';
debug ($value);
}
?>
and the error: Notice (8): Array to string conversion
I'm using php 5.6
Thanks for reply.
I use
$serviceMe = ""; //OR use beginning html
foreach( $tmp as $t ) $serviceMe .= '<tr>' . $t . '</tr>';
$serviceMe .= ""; // Rest of the needed html
Make absolutely sure what type of is your $value. Is it integer,float,string,object,array... etc
I think your error comes from trying to convert array to string without proper handling.
$array = new array(
'key' => $value,
'key2' => $value2,
'key3' => $value3,
);
$string = "" . $array; //throws error!

Dynamic parameter JSON to WHERE in PHP

I have JSON Response Request and want make one variable $Where from them, this the JSON pattern :
"filter":
{"filters":[
{"logic":"and","filters":[
{"field":"NAMA","operator":"eq","value":"Rahmat"},
{"field":"NAMA","operator":"eq","value":"Rosadi"}
]},{"logic":"or","filters":[
{"field":"NIPK","operator":"eq","value":"1919191919"},
{"field":"NIPK","operator":"eq","value":"818181818181"}
]},{"logic":"and","filters":[
{"field":"JK","operator":"eq","value":"P"},
{"field":"JK","operator":"eq","value":"L"}
]}
],
"logic":"and"}
Can anyone tell me how make thats patter to singgle row PHP variable like this :
$Where = "(NAMA = 'Rahmat' or NAMA = 'Rosadi') and (NIPK = '1919191919' or NIPK != '818181818181') and (JK='P' AND JK='L')"
Sorry for my bad english.
You can enumerate the filters list into PHP arrays, building each of them as a list of SQL OR values, then join them with implode(' OR ', ...); and further implode the arrays in a list of ' AND ' clauses.
This approach loses much of the flexibility allowed from your JSON setup, though; it can be extended to an AND-list of either OR-clauses or single clauses, and maybe coalesce OR clauses for the same field using the IN syntax, but not much more.
You can look to algorithm that convert from RPN notation to algebraic to look for a more powerful (albeit more complex) approach.
The simple version is
$ops = array(
'eq' => '=',
'ne' => '!=',
'gt' => '>',
'lt' => '<',
'ge' => '>=',
'le' => '<=',
// CHECK THIS OUT, FIX & COMPLETE
);
$arr_Filters = array();
foreach($filters as $filter)
{
/* $filter is a set of subfilters:
{"logic":"and","filters":[
{"field":"NAMA","operator":"eq","value":"Rahmat"},
{"field":"NAMA","operator":"eq","value":"Rosadi"}
]},
which we see as:
*/
$logic = $filter['logic'];
$arr_Filter = array();
foreach($filter['filters'] as $fov)
{
$op_f = $fov['operator'];
$op = $ops[$op_f];
$value = /* FUNCTION TO SQL ESCAPE A VALUE */ $fov['value'];
$value = is_numeric($value) ? $value : "'".$value."'";
$arr_Filter[] = "$fov[field] $op $value";
}
$arr_Filters[] = '('.implode(' ' . $filter['logic'] . ' ', $arr_Filter).')';
}
$sql_filter = 'WHERE ' . implode(' AND ', $arr_Filters);
Using json_decode() an object can be retrieved that can be manipulated thus:
// ($ops omitted, same as above)
$arr_Filters = array();
foreach($filters->filter->filters as $filter)
{
/* $filter is a set of subfilters:
{"logic":"and","filters":[
{"field":"NAMA","operator":"eq","value":"Rahmat"},
{"field":"NAMA","operator":"eq","value":"Rosadi"}
]},
which we see as:
*/
$logic = $filter->logic;
$arr_Filter = array();
foreach($filter->filters as $fov)
{
$op_f = $fov->operator;
$op = $ops[$op_f];
$value = /* FUNCTION TO SQL ESCAPE A VALUE */ $fov->value;
$value = is_numeric($value) ? $value : "'".$value."'";
$arr_Filter[] = "{$fov->field} $op $value";
}
$arr_Filters[] = '('.implode(' ' . $filter->logic . ' ', $arr_Filter).')';
}
$sql_filter = 'WHERE ' . implode(' ' . $filters->filter->logic . ' ', $arr_Filters);

Can I display the array key and value without using foreach?

I don't like to use the foreach for every little array, I hear'd it is also possible to replace it with some array_ function, but I forget the function name.
This is what I wan't to reach:
$down = array (
"file.rar" => $l->get()->fileDesc(),
"file1.rar" => $l->get()->clientDesc()
);
normally, I'm using this to display the data:
foreach ( $down as $key => $value )
$data .= $key . ' = ' . $value . '<br/>';
So it'll return:
//echo $data;
file.rar = File Description One
file1.rar = Client Description
It there a way to prevent from using the foreach and display the same $data anyway?
I'm just curious, so please be nice.
Why don't you just write your own function?
function print_array($down) {
$data = '';
foreach ( $down as $key => $value )
$data .= $key . ' = ' . $value . '<br/>';
return $data;
}
You can use print_r with true on the second parameter, but I would suggest to use a foreach (as I say in my comment)
<?php
$data = print_r($down, true);
?>
well the only time you would need to use a foreach is for a dynamic array. if thats not the case, just use isset to find out what is set. you can also use count if your just trying to figure out how big an array is.

Using foreach inside of a defined array PHP

Is there anyway to loop through an array and insert each instance into another array?
$aFormData = array(
'x_show_form' => 'PAYMENT_FORM',
foreach($aCartInfo['items'] as $item){
'x_line_item' => $item['id'].'<|>'.$item['title'].'<|>'.$item['description'].'<|>'.$item['quantity'].'<|>'.$item['price'].'<|>N',
}
);
Not directly in the array declaration, but you could do the following:
$aFormData = array(
'x_show_form' => 'PAYMENT_FORM',
'x_line_item' => array(),
);
foreach($aCartInfo['items'] as $item){
$aFormData['x_line_item'][] = $item['id'].'<|>'.$item['title'].'<|>'.$item['description'].'<|>'.$item['quantity'].'<|>'.$item['price'].'<|>N';
}
Yes, there is a way ; but you must go in two steps :
First, create your array with the static data
And, then, dynamically add more data
In your case, you'd use something like this, I suppose :
$aFormData = array(
'x_show_form' => 'PAYMENT_FORM',
'x_line_item' => array(), // right now, initialize this item to an empty array
);
foreach($aCartInfo['items'] as $item){
// Add the dynamic value based on the current item
// at the end of $aFormData['x_line_item']
$aFormData['x_line_item'][] = $item['id'] . '<|>' . $item['title'] . '<|>' . $item['description'] . '<|>' . $item['quantity'] . '<|>' . $item['price'] . '<|>N';
}
And, of course, you should read the section of the manual that deals with arrays : it'll probably help you a lot ;-)
You mean something like this :
$aFormData = array(
'x_show_form' => 'PAYMENT_FORM',
'x_line_item' => array(),
);
foreach($aCartInfo['items'] as $item) {
$aFormData['x_line_item'][] = implode('<|>', $aCartInfo['items']).'<|>N',
}

Categories