PHP convert columns to query - php

I have a table on the frontend, where the user can choose what types of columns he wants.
After submitting the form I get the array with selected columns.
For instance the user select following columns:
$columns = ["campaign_start_time", "campiagn_end_time", "campaign_id", "campaign_budget", "adset_name", "ad_name"]
Now I have to make the request to the facebook api, but facebook api only request query in form:
$query = "campaign{start_time, end_time, id, budget}, adset{name}, ad{name}"
Here is my question, what is the best way to convert $columns to $query in PHP language?

If you can construct your submitted data to be in this form:
Array
(
[campaign] => Array
(
[0] => start_time
[1] => end_time
[2] => id
[3] => budget
)
[adset] => Array
(
[0] => name
)
[ad] => Array
(
[0] => name
)
)
Maybe using inputs or other constructs such as:
name="campaign[]" value="start_time"
name="campaign[]" value="end_time"
Then looping and building the query with the keys and values will do it:
foreach($columns as $key => $val) {
$query[] = $key . '{' . implode(',', $val) . '}';
}
$query = implode(',', $query);
Otherwise you'll need to parse it to get what you need first, then execute the loop above using $result instead:
foreach($columns as $val) {
preg_match('/^([^_]+)_(.*)/', $val, $match);
$result[$match[1]][] = $match[2];
}

This solution splits apart the values based on underscores and then joins them back together as nested values based on the category/key. Note that this doesn't check for items that don't have a "prefix".
<?php
$columns = ["campaign_start_time", "campaign_end_time", "campaign_id", "campaign_budget", "adset_name", "ad_name"];
$criteria = [];
foreach( $columns as $column ){
$pieces = explode('_',$column);
$category = array_shift($pieces);
if( !isset($criteria[$category]) ){
$criteria[$category] = [];
}
$criteria[$category][] = implode('_', $pieces);
}
$queryPieces = [];
foreach($criteria as $category => $values){
$queryPieces[] = $category.'{'.implode(', ', $values).'}';
}
$query = implode(', ', $queryPieces);

Related

Merge multiple arrays into one with unique values php [duplicate]

This question already has answers here:
Create flat array of individual values from rows of comma-separated values fetched from a database table
(5 answers)
Closed 6 months ago.
I know that there are a lot of similar threads on Stack Overflow, but none of them works in my case.
My goal is to get the unique show genres from the database. They are stored (1,2,3 or more) comma separated in the show_genres column.
$link = mysqli_connect('127.0.0.1', 'root', 'pw', 'db');
$query = "SELECT show_genres FROM tv_shows";
$result = mysqli_query($link, $query);
foreach ($result as $value) {
$sh_genres = $value['show_genres'];
$sh_genres_array = array_map('trim', explode(',',$sh_genres));
// $doesnt_work = call_user_func_array("array_merge",
$sh_genres_array); // doesn't work for me
echo '<pre>' . var_export($sh_genres_array, true) . '</pre>';
}
My result is as follows:
array (
0 => 'Drama',
1 => 'Action',
2 => 'Crime',
)
array (
0 => 'Drama',
1 => 'Crime',
)
array (
0 => 'Drama',
1 => 'Thriller',
)
array (
0 => 'DIY',
)
array (
0 => 'Drama',
1 => 'Mystery',
2 => 'Supernatural',
)
However, I need just one array which contains the unique values, such as:
array (
0 => 'Drama',
1 => 'Mystery',
2 => 'Supernatural',
4 => 'Thriller',
5 => 'DIY',
6 => 'Crime',
7 => 'etc...'
)
If I try to create some array before the foreach loop and then store the data into it, such approach doesn't give a result as well.
Perhaps, there is a more simple solution by the means of SQL!?!?
Please try this code
In SQL
$query = "SELECT show_genres FROM tv_shows GROUP BY show_genres";
In PHP
$newArray = array();
foreach ($result as $value) {
$sh_genres = $value['show_genres'];
$sh_genres_array = array_map('trim', explode(',',$sh_genres));
$newArray = array_merge($newArray , $sh_genres_array );
}
$newUniqueArray = array_unique($newArray);
try using this code
$link = mysqli_connect('127.0.0.1', 'root', 'pw', 'db');
$query = "SELECT show_genres FROM tv_shows";
$result = mysqli_query($link, $query);
$sh_genres_array = [];
foreach ($result as $value) {
$sh_genres = $value['show_genres'];
$sh_genres_array = array_merge(
$sh_genres_array ,
array_map('trim', explode(',',$sh_genres))
);
}
echo '<pre>' . var_export(array_unique($sh_genres_array), true) . '</pre>';
Update
Please consider normalizing your database
Not sure but try this.
$genre_arr = RecursiveIteratorIterator(new RecursiveArrayIterator($sh_genres_array));
$unique_genre = array_unique($genre_arr);

Parse php array to make insert statement

Hi I have an array like this:
$datas =
[
'name_1'=>'John',
'name_2' =>'Mickey',
'settings_1' => 'Settings 1',
'settings_2' => 'Settings 2'
]
foreach($datas as $data){
//get items here...
}
How to pair or parse those items to make insert statement like this:
INSERT INTO table (name, settings)VALUES('John','Settings 1');
INSERT INTO table (name, settings)VALUES('Mickey','Settings 2');
Any idea? Thanks in advance.
This code could be usefull for creating array of arrays. Considering array keys will be name_x and settings_x
foreach($datas as $key=>$value){
// explode each key of the array
$keys = explode('_',$key);
$name = 'name_'.$keys[1];
$settings = 'settings_'.$keys[1];
// to generate array
$new_array[$keys[1]]=array('name'=>$datas[$name], 'settings'=>$datas[$settings]);
}
print_r($new_array);
Loop the $new_array for insert query.
Output :
Array
(
[1] => Array
(
[name] => John
[settings] => Settings 1
)
[2] => Array
(
[name] => Mickey
[settings] => Settings 2
)
)
$datas =
[
'name_1'=>'John',
'name_2' =>'Mickey',
'settings_1' => 'Settings 1',
'settings_2' => 'Settings 2'
];
$results = [];
foreach($datas as $index=>$data){
//create an array out of $index breaking it at the '_'
//so array will be $parts = [0=>'name', 1=>'1'];
$parts = explode('_', $index);
//'name_1'=>'John' = $results[1]['name'] = 'John';
$results[$parts[1]][$parts[0]] = $data;
}
//batch insert new formed array
//INSERT INTO tbl_name (name, settings) VALUES $results;
Check this, you must do some intermediate steps. Comments on code!!
$datas =
[
'name_1'=>'John',
'name_2' =>'Mickey',
'settings_1' => 'Settings 1',
'settings_2' => 'Settings 2'
];
$data_final = [];
foreach($datas as $key=>$value){
$keyX = preg_replace('/^(.+)_(\d+)$/', '$1', $key);// get the "type" (name, setting)
$keyY = preg_replace('/^(.+)_(\d+)$/', '$2', $key);// get the "index" (_1, _2 without "_")
$data_final[$keyY][$keyX] = $value; // put in result
}
// make queries
$sql = [];
foreach($data_final as $datas){
$fields = implode(", ", array_keys($datas)); //implode the keys to sql fields
$values = implode(", ", array_map(function($a){return "'$a'";}, array_values($datas)));//implode values to sql values adding ''. WARNING: This not escape values. Use escape string function on mysqli obj or PDO to the right escape
$sql[] = "INSERT INTO table ($fields) VALUES ($values);"; // populate query
}
$sql = implode("\n", $sql); // implode with new line
print_r($sql); //results
IMPORTANT:
You must have the right syntax "field_number" to respect the procedure
You can use even with one or more of two fields per record
You can use any field name, always respecting the "field_number" syntax
DEMO HERE

json code integrated with php

I have these following code. could anyone please explain it to me about these code, I did not get all of them.
here is the code
$query = $_SERVER['QUERY_STRING'];
$query = explode('&', $_SERVER['QUERY_STRING']);enter code here
$params = array();
foreach ($query as $param) {
list($name, $value) = explode('=', $param, 2);
$params[urldecode($name)][] = urldecode($value);
}
//echo jsonEncode($params);
$categories = implode(", ", $params['categories']);
$types = implode(", ", $params['type']);
I am confused about these two variables "$param" & "$params"
If a page is accessed via any query string, $_SERVER['QUERY_STRING'] fetches that query string.
for example, if you call url in your browser like this
http://example.com/index.php?name=msk&job=developer
then $_SERVER['QUERY_STRING'] contain following data
"name=msk&job=developer"
and explode() used to convert string to array where delimeter is &
$query = explode('&', $_SERVER['QUERY_STRING']);
now $query contain array with following data
Array
(
[0] => "name=msk"
[1] => job=developer"
)
.
$params = array(); //created to hold $_SERVER['QUERY_STRING'] array of strings
foreach ($query as $param) {
list($name, $value) = explode('=', $param, 2);
//above line try to convert "name=msk" into array like this ["name"] => array([0] = msk)
//list() function is used to assign values to a list of variables in one operation.
$params[urldecode($name)][] = urldecode($value);
}
$params contain following array data
(
["name] => Array
(
[0] => msk
)
[job] => Array
(
[0] => developer"
)
)
echo json_encode($params);
json_encode() used for converting php array to JSON
{"\"name":["msk"],"job":["developer\""]}
and come to your doubt
$param is just a loop iterator
$params is array used for holding $_SERVER['QUERY_STRING'] data

loop through associative array and passed key in sql query

i have the requirement, when user checks checkbox, i m getting checkbox value as key value pair
Array(
[checkboxname] => Array(
[1] => on
[5] => on
[12] => on
[15] => on
)
)
i have to pass this key in sql statement and retrive another checkbox from this key.
this is query i have to write
foreach($array as $key => $value)
{
}
$reult = $this->db->get_where('select_another_value ', array('id' => $key))->result_array();
what should i write in query instead of $key
Suppose you want to get all checked check boxes value from db, and Id inside array key and use where_in() method and pass array keys in array, see below sample code
$all_keys = array_keys($arr['checkboxname']);
$result = $this->db->where_in('id', $all_keys)
->get('select_another_value')->result_array();
Try with -
foreach($array as $key => $value){
$reult[] = $this->db->get_where('select_another_value ', array('id' => $key))->result_array();
}
Or you can try with -
$keys = array();
foreach($array as $key => $value){
$keys[] = $key;
}
if (count($keys) > 1) {
$where = " id IN (".implode(',', $keys).")";
} else {
$where = " id = '".$key[0]."'";
}
$this->db->where($where);
If you want to avoid running query inside loop.

Bidimensional array generated dynamically

I'm working with dynamic data, so I'm trying to put that data into a bidimensional array.
I need a structure like this:
$array['something1'] = array ( 'hi1' => 'there1' , 'hi2' => 'there2' );
All this data is dynamically generated by a foreach, ex.:
$list = array ( 0 => 'something;hi1;there1' , 1 => 'something;hi2;there2' );
foreach ( $list as $key => $data )
{
// extract data
$columns = explode ( ';' , $data );
// set data
$items[$columns[0]] = array ( $columns[1] => $columns[2] );
}
How Can I do the previously described?
Right now the script is stepping over the previous key getting something like this:
$array['something1'] = array ( 'hi2' => 'there2' );
I hope you can help me.
Thanks.
The problem is that you are overwriting the value for the key when it already exists. You should modify to something like:
foreach ( $list as $key => $data )
{
// extract data
$columns = explode ( ';' , $data );
$outer_array_key = $columns[0];
$key = $columns[1];
$value = $columns[2];
// set data
$items[$outer_array_key][$key] = $value;
}
Here is how it can be done:
$list = array ( 0 => 'something;hi1;there1' , 1 => 'something;hi2;there2' );
$newlist =array();
foreach($list as $k=>$v){
$items = explode(';',$v);
$newlist[$items[0]][$items[1]]=$items[2];
}
echo "<pre>";
print_r($newlist);
echo "</pre>";
//output
/*
Array
(
[something] => Array
(
[hi1] => there1
[hi2] => there2
)
)*/
?>
Change your set data with something like this :
if(!array_key_exists($columns[0], $items))
$items[$columns[0]] = array();
$items[$columns[0]][$columns[1]] = $columns[2];

Categories