Since I cant use JSON_UNESCAPED_UNICODE because my php is < 5.4, I have tried some replacements from json_encode() manual page:
$final = array (
0 => array (
'id' => 26629,
'content' => 'преди 5 сек'
),
1 => array (
'id' => 26628,
'content' => 'преди 5 сек'
),
2 => array (
'id' => 26627,
'content' => 'преди 5 сек'
)
);
$myDirtyString = json_encode($final);
$myDirtyString = str_replace("\/","/",$myDirtyString);
$myDirtyString = str_replace('"','\\"',$myDirtyString);
echo $myCleanedString = json_decode('"'.$myDirtyString.'"');
And the result is:
[
{"id":"26629","timestamp":"преди 5 сек"},
{"id":"26628","timestamp":"преди 5 сек"},
{"id":"26625","timestamp":"¿Ñеди 5 Ñек"}
]
Why the last item is such a mess?
I tried
header('Content-Type: application/json; charset=utf-8');
...but still dosent work.
If your on a version of PHP before 5.4, this might help:
<?php
if (!function_exists('json_encode')) {
function json_encode($data) {
switch ($type = gettype($data)) {
case 'NULL':
return 'null';
case 'boolean':
return ($data ? 'true' : 'false');
case 'integer':
case 'double':
case 'float':
return $data;
case 'string':
return '"' . addslashes($data) . '"';
case 'object':
$data = get_object_vars($data);
case 'array':
$output_index_count = 0;
$output_indexed = array();
$output_associative = array();
foreach ($data as $key => $value) {
$output_indexed[] = json_encode($value);
$output_associative[] = json_encode($key) . ':' . json_encode($value);
if ($output_index_count !== NULL && $output_index_count++ !== $key) {
$output_index_count = NULL;
}
}
if ($output_index_count !== NULL) {
return '[' . implode(',', $output_indexed) . ']';
} else {
return '{' . implode(',', $output_associative) . '}';
}
default:
return ''; // Not supported
}
}
}
?>
Related
$main= array(
"data"=>array(
"userid"=>"1",
"$str",
"acc_id"=>"10",
"fi"=>"3"
),
"next"=>"4"
);
Here i added
"value1"=>"$row->field1",
"value2"=>"$row->field2",
"value3"=>"$row->field3",
"value4"=>"$row->field4"
using $str Dynamically with the help of for loop because it is dynamic not fixed.
I want to make this array like the below, so it can work and print correct output - It's my desired output(I want this array like this to be working)
array(
"data"=>array(
"userid"=>"$row->uid",
"value1"=>"$row->field1",
"value2"=>"$row->field2",
"value3"=>"$row->field3",
"value4"=>"$row->field4",
"acc_id"=>"$acc_id",
"tloop"=>"$timeloopc"
),
"next"=>"$next"
);
Output is -
But array taking the value of $str as string and when i print thisit shows output -
Array (
[data] => Array (
[user1] => 1
[0] => "value1"=>"$row->field1",
"value2"=>"$row->field2",
"value3"=>"$row->field3",
"value4"=>"$row->field4",
"value5"=>"$row->field5"
[user2] => 2
[fi] => 3
)
[next] => 4
)
The Above output is issue... Here array processing some key and value but not processing $str value... it's taking it as sting.
It's now processing the $str values as string from "value1" and "field1"..to..4
Help me to dynamically fill key and value in an associative array using for loop.
In the array "value1 and field1" - here numbers are dynamic - "value2" and "field2"...
When i am making array dynamic, it's not working like array. If i make it static it works fine.
So please help me to make $str value from string to array value(object)...
Here is complete code -
<?php
$ct = 4;
$str = '';
for($cunt=1; $cunt<=$ct; $cunt++)
{
$valu= '"value';
$cuntc = $cunt.'"';
$rw = '"$row';
$fild= "field";
$cp = $valu.$cuntc."=>".$rw."->".$fild.$cuntc;
$str .= $cp . ',';
}
//trim the , from last value
$str = rtrim($str, ",");
$main= array("data"=>array("userid"=>"1","$str","acc_id"=>"10","fi"=>"3"),"next"=>"4");
print_r($main);
?>
I don't know what exactly you want.
There is a code, which build array you'd like to have:
$main= array(
"data"=>array(
"userid"=>"1",
"$str",
"acc_id"=>"10",
"fi"=>"3"
),
"next"=>"4"
);
$ct = 4;
$subArray = array();
$resultArray = array();
$resultArray['data']['userid'] = '$row->uid';
for($cunt=1; $cunt<=$ct; $cunt++)
{
$valu= 'value';
$rw = 'row';
$fild= "field";
$resultArray['data'][$valu . $cunt] = '$' . $rw . '->' . $fild .$cunt;
}
$resultArray['data']['acc_id'] = '$acc_id';
$resultArray['data']['tloop'] = '$timeloopc';
$resultArray['next'] = '$next';
echo "<pre>";
var_dump($resultArray);
echo "</pre>";
But if you don't need restricted key ordering, you can use something like this (it's rebuild $main array):
$main= array(
"data"=>array(
"userid"=>"1",
"$str",
"acc_id"=>"10",
"fi"=>"3"
),
"next"=>"4"
);
$fields = array();
for($cunt=1; $cunt<=$ct; $cunt++)
{
$valu= 'value';
$rw = 'row';
$fild= "field";
$fields[$valu . $cunt] = '$' . $rw . '->' . $fild .$cunt;
}
foreach ($fields as $key => $value) {
$main['data'][$key] = $value;
}
And there is solution with functions:
function generateFieldArray($keyName, $obj, $field, $rowCount)
{
$resultArray = array();
for($count=1; $count<=$rowCount; $count++)
{
$resultArray[$keyName . $count] = '$' . $obj . '->' . $field .$count;
}
return $resultArray;
}
function buildMainArray($inputArray, $keyName, $obj, $field, $rowCount)
{
$arrayToAdd = generateFieldArray($keyName, $obj, $field, $rowCount);
foreach ($arrayToAdd as $key => $value) {
$inputArray['data'][$key] = $value;
}
return $inputArray;
}
function buildMainArray2($inputArray, $keyName, $obj, $field, $rowCount)
{
$resultArray = array();
$resultArray['data']['userid'] = '$row->uid';
$arrayToAdd = generateFieldArray($keyName, $obj, $field, $rowCount);
foreach ($arrayToAdd as $key => $value) {
$resultArray['data'][$key] = $value;
}
$resultArray['data']['acc_id'] = '$acc_id';
$resultArray['data']['tloop'] = '$timeloopc';
$resultArray['next'] = '$next';
return $resultArray;
}
$main= array(
"data"=>array(
"userid"=>"1",
"$str",
"acc_id"=>"10",
"fi"=>"3"
),
"next"=>"4"
);
$result = buildMainArray($main, 'value', 'row', 'field', 4);
// or
$result = buildMainArray2($main, 'value', 'row', 'field', 4);
I'm having a hard time checking for empty values in my associative array. And if a value is empty/null replace it with the wording "not entered"
My $_SESSION['gift'] array:
Array
(
[0] => Array
(
[giftGiveMy] => 1a
[giftTo] => 2a
)
[1] => Array
(
[giftGiveMy] => 1b
[giftTo] => '' //### empty ###
)
)
if (empty($_SESSION['gift']) && 0 !== $_SESSION['gift']) {
$gifts = "No specific gifts identified.\n";
} else {
$gifts = [];
foreach( $_SESSION['gift'] as $value) {
$gifts[] = "I give my ". $value['giftGiveMy'] ." to ". $value['giftTo'] .".\n";
}
$gifts = join($gifts);
}
The above outputs:
I give my 1a to 2a.
I give my 1b to .
I would like it read:
I give my 1a to 2a.
I give my 1b to not entered.
You can replace all empty and NULL value with not entered with the help of array_walk_recursive and use you code as it is
array_walk_recursive($arrayMain, 'not_entered');
function not_entered(& $item, $key) {
if (($item === "") || ($item ==NULL)){
$item = "not entered";
}
}
var_dump($arrayMain);
Just use foreach to loop all values and check if it's empty
$emptyText = '<b>not entered</b>';
// `empty` will also be true if element does not exist
if (empty($_SESSION['gift'])) {
$gifts = "No specific gifts identified.\n";
} else {
$gifts = [];
foreach($_SESSION['gift'] as $value) {
$myGive = !empty($value['giftGiveMy']) ? $value['giftGiveMy'] : $emptyText;
$giftTo = !empty($value['giftTo']) ? $value['giftTo'] : $emptyText;
$gifts[] = "I give my {$myGive} to {$giftTo}.";
}
$gifts = implode("\r\n", $gifts); // Or `<br/>` if outputted to HTML
}
You should modify your code and write it this way:
if (!isset($_SESSION['gift']) || empty($_SESSION['gift'])) {
$gifts = "No specific gifts identified.\n";
} else {
foreach( $_SESSION['gift'] as $value) {
$gift_to = !empty($value['giftTo']) ? $value['giftTo'] : '<strong>Not entered<strong>';
$gifts[] = "I give my ". $value['giftGiveMy'] ." to ". $gift_to .".\n";
}
}
You might want to try this:
if (empty($_SESSION['gift']) && 0 !== $_SESSION['gift']) {
$gifts = "No specific gifts identified.\n";
} else {
$gifts = [];
foreach( $_SESSION['gift'] as $value) {
$gifts[] = "I give my ". $value['giftGiveMy'] ." to ". (!empty($value['giftTo']) ? $value['giftTo'] : '<b>not entered</b>') .".\n";
}
$gifts = join($gifts);
}
If you would like to make it a little cleaner you could extract the ternary operator into something like this;
$giftTo = !empty($value['giftTo']) ? $value['giftTo'] : '<b>not entered</b>';
$gifts[] = "I give my ". $value['giftGiveMy'] ." to ". $giftTo .".\n";
Try:
$arr = $_SESSION['gift'];
foreach($arr as $key => $array) {
if($array['giftGiveMy'] == null || empty($array['giftGiveMy'])) {
$arr[$key]['giftGiveMy'] = 'not entered.';
}
if($array['giftTo'] == null || empty($array['giftTo'])) {
$arr[$key]['giftTo'] = 'not entered.';
}
}
I'd write that this way:
$gifts = "No specific gifts identified.\n";
$filter = function($str) {
return empty($str) ? 'not entered' : $str;
};
if(!empty($_SESSION['gift'])) {
$gifts = '';
array_walk($_SESSION['gift'], function($given) use(&$gifts,$filter){
$gifts .= 'I give my ' . $filter($given['giftGiveMy']) . ' to ' . $filter($given['giftTo']) . ".\n";
});
}
You can use for the below code also there is no need any extra Php functions.
$arr = array(
0 => array(
'giftGiveMy' => '1a',
'giftTo' => '2a'
),
1 => array(
'giftGiveMy' => '1b',
'giftTo' => ''
)
);
$str = '';
if (!empty($arr)) {
foreach ($arr as $key => $value) {
if ($value['giftGiveMy'] == '')
$value['giftGiveMy'] = 'not entered';
if ($value['giftTo'] == '')
$value['giftTo'] = '<strong>not entered</strong>';
//$new[$key] = $value;
$str .= "I give my " . $value['giftGiveMy'] . " to " . $value['giftTo'] . "<br />";
}
}else {
$str = 'No specific gifts identified.<br />';
}
echo $str;
This validates an associative array with empty() (see array_filter), but may not respond to the original question.
<?php
$var = array();
$var['position'] = 'executive';
$var['email'] = 'a#email.com';
$var['message'] = 'This is the message';
$var['name'] = 'John Doe';
$var['telephone'] = '123456789';
$var['notneededparam'] = 'Nothing';
$expectedParams = ['position', 'email', 'message', 'name', 'telephone'];
$params = array_intersect_key($var, array_flip($expectedParams));
// check existence of keys and that they are valid
if(count($params) != count($expectedParams) || count(array_filter($params)) != count($expectedParams)){
echo "not valid\n";
die();
}
extract($params);
var_dump($name);
Other functions used here: array_flip(), array_intersect_key(), count(), extract(), var_dump(),
It's a function in my class. I have no idea for imploding $newConditions with ( OR ) ( AND ).
Anybody have an idea ?
// #GETSSQ = Get Secured Select Query
function getSSQ($query) {
$conDelimiters = array(' OR ',' AND '); // Condition Delimiters
$fivaDelimiters = array('LIKE','<=>','<>','=>','<=','!=','=','<','>'); // Field & Value delimiters {Operators}
$conditions = preg_split("/(".implode('|',$conDelimiters).")/", $query);
$newConditions = array();
$operator = array("operator" => null);
foreach ($conditions as $idx => $cond) {
$operator["index"] = strlen($cond);
foreach ($fivaDelimiters as $sym) {
$pos = strpos($cond,$sym);
if ($pos === false)
continue;
else {
if ($pos < $operator['index']) {
$operator['index'] = $pos;
$operator['operator'] = $sym;
}
}
}
// Operatör bölme işlemine devam et...
$parts = array();
if ($operator['operator'] === null) {
$error = array(
"error" => "Koşullar arası yazım hatası tespit edildi. [".$this->options['connectionType'].":".$query."]",
"code" => "008"
);
$this->showError($error);
continue;
} else {
$condParts = explode($operator['operator'],$cond);
foreach ($condParts as $idx => $val) {
$condParts[$idx] = trim($val);
}
$parts['field'] = $this->__getSSQ_editFields($condParts[0]);
$parts['operator'] = $this->__getSSQ_editOperators($operator['operator']);
$newValue = $condParts[1];
if (count($condParts) > 2) { // If condition value has an operator character set
unset($condParts[0]);
$newValue = implode($operator['operator'],$condParts);
}
if (preg_match("/^['|\"](.*?)['|\"]$/", $newValue)) { // If value has {'} or {"} character begin & end , remove it
$newValue = substr($newValue, 1, (strlen($newValue)-2));
}
$newValue = $this->__getSSQ_editValues($newValue);
$parts['value'] = $newValue;
} #ENDIF OPERATOR === NULL
$newConditions[] = $parts['field'].' '.$parts['operator'].' '.$parts['value'];
} #END FOREACH CONDITIONS
var_dump($newConditions);
}
For Example My Function :
$condition = "id=5 AND parentCategory=2 AND firstName LIKE 'B%' AND usingMobile = 'true'";
$db = new XXClass();
$db->getSSQ($condition);
This output =>
array (size=4)
0 => string 'id = '5'' (length=8)
1 => string 'parentCategory = '2'' (length=20)
2 => string 'firstName LIKE 'B%'' (length=19)
3 => string 'usingMobile = 'true'' (length=20)
I can reach Fields , Operators , Values with __getSSQ_editXXXXX functions
I'm facing a problem for several days now, and I'm staring blind at it, and can't seem to find the source myself.
I've made a class to execute my queries. The actual query executing part looks like this:
<?php
public function query( $method, $table, $data, $where_text='', $where_data='' ) {
$this->check_db_status();
$method = strtoupper( $method );
$fieldsArray = array();
$valuesArray = array();
$paramsArray = array();
$format = '';
$queryText = '';
switch( $method ) {
case 'SELECT' :
$queryText = 'SELECT %s FROM ' . $table . ' ';
foreach( $data as $field => $value ) {
$fieldsArray[] = $value;
}
break;
case 'UPDATE' :
$queryText = 'UPDATE ' . $table . ' SET %s ';
foreach( $data as $field => $value ) {
$fieldsArray[] = $field.'=?';
$format .= $this->get_value_type( $value );
$paramsArray[] = $value;
}
break;
case 'DELETE' :
$queryText = 'DELETE FROM ' . $table . ' ';
break;
case 'INSERT' :
$queryText = 'INSERT INTO ' . $table . ' (%s) VALUES (%s) ';
foreach( $data as $field => $value ) {
$fieldsArray[] = $field;
$format .= $this->get_value_type( $value );
$valuesArray[] = '?';
$paramsArray[] = $value;
}
break;
default :
$this->get_error( 'Error in method switch' );
break;
}
if( $where_text ) {
$queryText .= $where_text;
if( $where_data ) {
foreach( $where_data as $value ) {
$format .= $this->get_value_type( $value );
$paramsArray[] = $value;
}
}
}
$fields = implode( ',', $fieldsArray );
$values = implode( ',', $valuesArray );
$query = sprintf( $queryText, $fields, $values );
// DEBUG
echo '<pre>';
echo 'query: ' . $query . '<br />
echo 'format: ' .' . $format . '<br />';
print_r( $paramsArray );
echo '</pre>';
$stmt = $this->mysqli->prepare( $query );
if( $stmt === false or $stmt == NULL ) {
$this->get_error( 'Error while preparing the statement' );
}
if( $format and $paramsArray )
call_user_func_array( 'mysqli_stmt_bind_param', array_merge( array( $stmt, $format ), $paramsArray ) );
if( $stmt->execute() ) {
$result = 0;
switch( $method ) {
case 'INSERT' :
$result = ($stmt->insert_id) ? $stmt->insert_id : true;
break;
case 'UPDATE' :
case 'DELETE' :
$result = ($stmt->affected_rows) ? $stmt->affected_rows : true;
break;
case 'SELECT' :
$meta = $stmt->result_metadata();
$fields = $result = array();
while ($field = $meta->fetch_field()) {
$var = $field->name;
$$var = null;
$fields[$var] = &$$var;
}
call_user_func_array(array($stmt,'bind_result'),$fields);
$i = 0;
while( $stmt->fetch() ) {
$result[$i] = array();
foreach( $fields as $k => $v)
$result[$i][$k] = $v;
$i++;
}
break;
}
$stmt->close();
$this->query_cnt++;
return $result;
}
else {
$this->get_error();
}
}
?>
Now I'm trying to make an other class to store my sessions in my own database. The write function looks like this:
<?php
public function write_session( $session_id, $session_data ) {
$query = $this->sql->query( 'INSERT', 'sessions', array( 'ses_id'=>$session_id, 'ses_time'=>time(), 'ses_start'=>time(), 'ses_data'=>$session_data, 'ses_check'=>$this->check ), 'ON DUPLICATE KEY UPDATE ses_time=?, ses_data=?', array(time(),$session_data));
if($query) {
return true;
}
else {
return false;
}
}
?>
I keep getting this error:
Warning: mysqli::prepare() [mysqli.prepare]: Couldn't fetch mysqli in /.../class.db.php on line 124
Line 124 is the line with $stmt = $this->mysqli->prepare( $query );. It is triggered by the first line of the write_session.
If put in a debug part in the database class to show the query, it gives this output:
query: INSERT INTO sessions (ses_id,ses_time,ses_start,ses_data,ses_check) VALUES (?,?,?,?,?) ON DUPLICATE KEY UPDATE ses_time=?, ses_data=?
format: [siissis]
Array
(
[0] => a98696a8416fc898f2c07e05f39735dc
[1] => 1402201705
[2] => 1402201705
[3] => test|s:11:"someValuess";
[4] => 40b17cb572d9bf5eaadad99b7904e0a4889a31d0
[5] => 1402201705
[6] => test|s:11:"someValuess";
)
Which seems fine to me.... what am I overlooking?
Edit
Table definition of sessions:
sessions (
ses_id varchar(32) NOT NULL,
ses_time int(11) NOT NULL,
ses_start int(11) NOT NULL,
ses_data text NOT NULL,
ses_check varchar(40) NOT NULL,
PRIMARY KEY (ses_id)
)
A pointed out in the link provided in the comments, your problem appears to be
4. You mixed OOP and functional calls to the database object.
Specifically, you use a mysqli object here
$stmt = $this->mysqli->prepare( $query );
But then proceed to make a functional mysqli call here
if( $format and $paramsArray )
call_user_func_array( 'mysqli_stmt_bind_param', array_merge( array( $stmt, $format ), $paramsArray ) );
So try replacing the code above with its corresponding OOP version
if($format and $paramsArray) {
$stmt->bind_param($format,$paramsArray);
}
Also replace
call_user_func_array(array($stmt,'bind_result'),$fields);
With
$stmt->bind_param($format,$fields);
http://www.php.net//manual/en/mysqli-stmt.bind-param.php
Implement __wakeup
Another possibility is that your db connection may have been closed due to serialization. Try reconnecting by implementing __wakup i.e.
public function __wakeup()
{
$this->mysqli = new mysqli('localhost', 'my_user', 'my_password', 'my_db');
}
Hi i have this code to output a array list
$Sql1 = "SELECT * FROM tabmp3
WHERE Mp3_Player = 1
";
$Query1 = mysql_query($Sql1, $Conn)or die(mysql_error($Conn));
$musicas = array();
while($Rs1 = mysql_fetch_array($Query1)){
$musicas[] = array( title => $Rs1['Musica_Nome'], autor => "Grupo Fronteiras", mp3 => "http://site/Musicas/".$Rs1["Disco_Id"]."/".$Rs1["Musica_Mp3"] );
}
echo ( json_encode($musicas) );
this output
[{"title":"Alegria do Pov\u00e3o","autor":"Grupo Fronteiras","mp3":"http:\/\/site\/Musicas\/3\/201302140204413c390efdb9957eebd8d85c262f2a4929.mp3"}, {"title":"Bem na moda da fronteira","autor":"Grupo Fronteiras","mp3":"http:\/\/site\/Musicas\/2\/20130214032235fabd12471ffc7790c9204f891919bca8.mp3"}]
i need to remove double quotes from keys and fix the http link to looks like this
[{title:"Alegria do Pov\u00e3o",autor:"Grupo Fronteiras",mp3:"http://site/Musicas/3/201302140204413c390efdb9957eebd8d85c262f2a4929.mp3"},{title:"Bem na moda da fronteira",autor:"Grupo Fronteiras",mp3:"http://site/Musicas/2/20130214032235fabd12471ffc7790c9204f891919bca8.mp3"}]
Thanks
Try this..I know it is not very good way to do it.. I am writing this to show you that you have to make the form that you wanted in your php code only.
$json = json_encode($musicas);
$json = preg_replace('/["]/', '' ,$json);
$json = str_replace(':',':"', $json);
$json = str_replace(',','",',$json);
$json = str_replace('}]','"}]',$json);
echo $json;
By this way you will acheive what you wanted. But please find something good way to do it.
The correct answer should be this, as commented by #AlvaroLouzada
$json = json_encode($musicas);
$json = preg_replace('/"([^"]+)"\s*:\s*/', '$1:', $json);
echo $json ;
I looked a lot for an elegant solution to fix this issue without doing changing things over javascript or just replace quotes via preg_replace (for the case that the values would contain quotes) and end up doing it by myself. even if it's too late, I hope it would help those who are looking for the same solution.
function json_encode_advanced(array $arr, $sequential_keys = false, $quotes = false, $beautiful_json = false) {
$output = "{";
$count = 0;
foreach ($arr as $key => $value) {
if ( isAssoc($arr) || (!isAssoc($arr) && $sequential_keys == true ) ) {
$output .= ($quotes ? '"' : '') . $key . ($quotes ? '"' : '') . ' : ';
}
if (is_array($value)) {
$output .= json_encode_advanced($value, $sequential_keys, $quotes, $beautiful_json);
} else if (is_bool($value)) {
$output .= ($value ? 'true' : 'false');
} else if (is_numeric($value)) {
$output .= $value;
} else {
$output .= ($quotes || $beautiful_json ? '"' : '') . $value . ($quotes || $beautiful_json ? '"' : '');
}
if (++$count < count($arr)) {
$output .= ', ';
}
}
$output .= "}";
return $output;
}
function isAssoc(array $arr) {
if (array() === $arr) return false;
return array_keys($arr) !== range(0, count($arr) - 1);
}
usage:
$array = [
'someField' => '"value"', // double quotes for string if needed
'labelField' => '"label"', // double quotes for string if needed
'boolean' => false,
'numeric' => 5,
'render' => [
'option' => 'function() {
console.log("Hello World!");
console.log(\'Hello World!\');
}',
],
];
echo json_encode_advanced($array);
result:
{
someField : "value",
labelField : "label",
boolean : false,
numeric : 5,
render : {
option : function() {
console.log("Hello World!");
console.log('Hello World!');
}
}
}
Instead of doing echo ( json_encode($musicas) );, do something like this:
$json_string = json_encode($musicas);
$json_string = str_replace('\/', '/', $json_string);
echo $json_string;