here i m doing a json_encode
public function get_posts_for_category($user_id,$category_id,$page)
{
$cat_id = $this->ApiModel->get_category_id($category_id);
$total_row = $this->ApiModel->get_category_posts_count($cat_id->category);
$per_page = 2;
$total_pages = $total_row / $per_page;
$posts = $this->ApiModel->get_category_posts($cat_id->category,$per_page,$page);
$data = array();
foreach($posts as $post)
{
$fav = $this->ApiModel->get_favourite($user_id,$post->pid);
if($fav == 1)
{
$status = 'true';
}
else
{
$status = 'false';
}
$array = array('pid' => $post->pid, 'uid' => $post->uid, 'title' => $post->title, 'slug' => $post->slug, 'content' => $post->content, 'image' => $post->image, 'time_stamp' => $post->time_stamp);
$data[] = array('page' => $page, 'posts' => $array, 'is_favorite' => $status);
}
echo strip_tags(json_encode($data));
}
the output i m getting from the above code is
But i want some thing like this
<?php
public function get_posts_for_category($user_id,$category_id,$page)
{
$cat_id = $this->ApiModel->get_category_id($category_id);
$total_row = $this->ApiModel->get_category_posts_count($cat_id->category);
$per_page = 2;
$total_pages = $total_row / $per_page;
$posts = $this->ApiModel->get_category_posts($cat_id->category,$per_page,$page);
$data = array();
foreach($posts as $post)
{
$fav = $this->ApiModel->get_favourite($user_id,$post->pid);
if($fav == 1)
{
$status = 'true';
}
else
{
$status = 'false';
}
$array = array('pid' => $post->pid, 'uid' => $post->uid, 'title' => $post->title, 'slug' => $post->slug, 'content' => $post->content, 'image' => $post->image, 'time_stamp' => $post->time_stamp, 'is_favorite' => $status);
$data[] = array('page' => $page, 'posts' => $array, 'total_posts' => count($posts), 'total_pages' => $total_pages);
}
echo strip_tags(json_encode($data));
}
?>
$return = array(
'page' => $page,
'total_posts' => $total_row,
'total_page' => $total_pages,
);
$data = [];
foreach($posts as $post)
{
$fav = $this->ApiModel->get_favourite($user_id, $post->pid);
if($fav == 1)
{
$status = 'true';
}
else
{
$status = 'false';
}
$array = array('pid' => $post->pid, 'uid' => $post->uid, 'title' => $post->title, 'slug' => $post->slug, 'content' => $post->content, 'image' => $post->image, 'time_stamp' => $post->time_stamp, 'is_favorite' => $status);
$data[] = $array;
}
$return['posts'] = $data;
$this->output->set_content_type('application/json');
$this->output->set_output(json_encode($return));
just replace this code with your foreach & echo statement.
You never should use strip_tags in conjunction with json_encode because you are already encoding the data it's receivers choice to do whatever he wants also in this process you might break the encoding.
Also you should use CI output library to send response you must not echo anything from your controller. see here https://ellislab.com/codeigniter/user-guide/libraries/output.html for more details
If you would like the numeric values to be output as such, (instead of strings) you may wish to try:
json_encode($return, JSON_NUMERIC_CHECK);
To format the outputted JSON nicely (indentation etc) use:
json_encode($return, JSON_PRETTY_PRINT);
You can use various combinations of the above as per json_encode's options.
As for the boolean values (instead of "true" and "false" returned as strings), you'll need to cast them as boolean types first:
$status = (bool) true;
Related
My PHP Code is the following, I need some assistance please:
//DB connection
$result = mysqli_query($con,"SELECT * FROM `clients`");
$info = array();
$count = 0;
$meta = array('page' => 1, 'pages' => 1, 'perpage' => -1, 'total' => 14, 'sort' => "asc", 'field' => "ID");
while ($row = $result->fetch_array(MYSQLI_ASSOC)) {
$info[$row['clientid']]['id'] = $row['id'];
$info[$row['clientid']]['name'] = $row['name'];
$info[$row['clientid']]['email'] = $row['email'];
$info[$row['clientid']]['cell'] = $row['cell'];
$count++;
}
$data = json_encode(array_values($info));
echo $data;
My Result;
[{"ID":1,"name":"A","email":"a#a.com","cell":"082"},
{"ID":2,"name":"B","email":"b#b.com","cell":"083"},
{"ID":3,"name":"C","email":"c#c.com","cell":"079"}]
The JSON should add the meta array with the following result:
{"meta":
{"page": 1,"pages": 1,"perpage": -1,"total": 3,"sort": "asc","field": ID"},
"data": [{"ID":1,"name":"A","email":"a#a.com","cell":"082"},
{"ID":2,"name":"B","email":"b#b.com","cell":"083"},
{"ID":3,"name":"C","email":"c#c.com","cell":"079"}]
},
Create array of required structure and json_encode it:
$data = json_encode(array(
'meta' => $meta,
'data' => array_values($info),
));
How do I convert an 'N' elements single dimensional array to 'N' level nested array in PHP ?
Example:
Input:
$input = array('Orange','Apple','Banana');
Expected Output:
$output = array(
'name' => 'Banana',
'sub_category' => array(
'name' => 'Apple',
'sub_category' => array(
'name' => 'Orange'
);
This is my code:
$categories = array('Orange','Apple','Banana');
$count = count($categories);
for($i=0;$i<=$count;$i++){
if(isset($categories[$i+1])){
$parent = $categories[$i+1]; // parent
$categories[$i+1]=array(
'name' => $categories[$i+1],
'sub_category' => array('name' => $categories[$i])
);
}
}
$categories = $categories[$count-1];
var_dump($categories);
My code is sloppy and I also get the following incorrect output:
$output = array(
'name' => 'Banana',
'sub_category' => array(
'name' => array(
'name' => 'Apple',
'sub_category' => array(
'name' => 'Orange'
);
);
Edit 1:
The problem/solution provided here does not seem to be answering my question.
You could use simple recursion technique:
function toNestedArray(array $input, array $result = [])
{
$result = ['name' => array_pop($input)];
if (count($input)) {
$result['sub_category'] = toNestedArray($input, $result);
}
return $result;
}
$categories = array('Orange','Apple','Banana');
$count = count($categories);
$categories2=array();
for($i=$count-1;$i>0;$i--){
if($i-2>-1){
$categories2=array(
'name'=>$categories[$i],
'sub_category'=>array('name'=>$categories[$i-1],'sub_categories'=>array('name'=>$categories[$i-2]))
);
}
}
echo "<pre>";
print_r($categories2);
echo "</pre>";
A simple option is to loop over the $input array, building the $output array from inside to out.
$output = array();
foreach ($input as $name) {
if (empty($output)) {
$output = array("name" => $name);
} else {
$output = array("name" => $name, "sub_category" => $output);
}
}
I was searching for a solution for my problem.
I have the code below:
while($row = mysql_fetch_array($resultQuery)){
$response = array(
'name' => $row['name'],
'data' => $row['data']
);
$responses[] = $response;
}
echo json_encode($responses);
The code will bring this result:
[{"name":"Name001","data":"1"},
{"name":"Name001","data":"2"},
{"name":"Name001","data":"3"},
{"name":"Name002","data":"4"},
{"name":"Name002","data":"5"},
{"name":"Name002","data":"6"}]
But I would like to have the result below:
[{"name":"Name001","data":[1,2,3]},
{"name":"Name002","data":[4,5,5]}
Each "Name" has its own ID, I would like in the "while" put each id with its own data.
Thank you for your help.
1. Update:
$id_name = "xx";
while($row = mysql_fetch_array($resultQuery)){
if($id !== $row['id']){
$response = array(
'name' => $row['name'],
'data' => array($row['data'])
);
$responses[] = $response;
}
$id_name = $row['id'];
}
echo json_encode($responses);
I am trying to check the ID first and if is different will bring to me:
[{"name":"Name001","data":["1"]},{"name":"Name002","data":["4"]}]
while($row = mysql_fetch_array($resultQuery))
$tmp[$row['name']][] = $row['data'];
foreach($tmp as $key => $item)
$responses[] = array('name' => $key, 'data' => $item);
echo json_encode($responses);
result
[{"name":"Name001","data":["1","2","3"]},{"name":"Name002","data":["4","5","6"]}]
I made a test here, hope you like.
$arr = array();
$arr[] = array(
'name' => 'val',
'data' => array(1, 2, 3)
);
$arr[] = array(
'name' => 'val',
'data' => array(1, 2, 3)
);
echo json_encode($arr);
Output:
[{"name":"val","data":[1,2,3]},{"name":"val","data":[1,2,3]}]
I currently writing an sms system for the end user. however, When I do the testing on the function i encounter sms credit deduction error.
There are three table in this function which are company, user and transaction.
I did many testing on this function. just cant get the credit deduction correctly.
for example there are 1000 credit in each table.
Initial value
company.sms_bal = 1000
user.user_credit_bal= 1000
transaction.transaction_balance = 1000
testing #1
deduct 1 credit on each table. it deducts correctly.
company.sms_bal = 999
user.user_credit_bal= 999
transaction.transaction_balance = 999
testing #2
deduct 2 credit on each table. it deducts incorrectly,
company.sms_bal = 997
user.user_credit_bal= 997
transaction.transaction_balance = 998 suppose to be 997.
P/S it does not always deduct incorrectly, just sometimes. Please kindly advice me. However if you are unsure my question just let me know I am willing to assist you.
Below is the function for your reference
function process_send_sms($data){
global $CONF, $Q, $OUT, $DB, $DBSH, $CODE, $LANG;
//
// check credit
//
$check_credit = check_credit($data);
if($check_credit['status'] == '100'){
//
// check credit and update credit and update track
//
// get $company_credit_bal
$DBSH->u_select('company', $company_data, array(
'company_id' => $company_id,
));
$company_credit_bal = $company_data['sms_bal'];
// get $user_credit_bal
$DBSH->u_select('user', $user_data, array(
'user_id' => $user_id,
));
$user_credit_bal = trim($user_data['user_credit_bal']);
$number_bulk_mt = trim($total_credit);
//
// update company
//
$rows = $DBSH->update(array(
'table' => 'company',
'set' => array(array('sms_bal = ?', $company_credit_bal - $number_bulk_mt),),
'where' => array(array('company_id = ?', $company_id),),));
$rows = $DBSH->update(array(
'table' => 'user',
'set' => array(array('user_credit_bal = ?', $user_credit_bal - $number_bulk_mt),),
'where' => array(array('user_id = ?', $user_id),),));
}else{
$return_data['error'] = $check_credit['error'];
}
if($check_credit['status'] == '100'){
//
// insert to the track
//
$arr = debug_backtrace();
$function_name = $arr[0]["function"];
$data = array(
'no_phones' => $total_credit,
'company_id' => $company_id,
'user_id' => $user_id,
'msg_type' => $function_name,
'track_mt_create_time' => $timestr,
'track_mt_update_date' => $timestr,
);
$DBSH->u_insert('bulk_mt_log_track', $data);
$ref_id = $DBSH->u_lastid('bulk_mt_log_track');
if($sendsmscsv == 'Y'){
foreach($phone_tem as $k => $v){
$phone_no = $v['phone'];
$message = $v['message'];
$coding = 1;
if($v['lang'] == '2'){
$coding = 3;
}
$check_credit = $credit_class->check_per_credit($phone_no,$is_intern);
$send_c_code = $check_credit['c_code' ];
$per_credit = $check_credit['per_credit'];
if($phone_no){
do{
$msgid = session_get()."_".$user_id;
$check_valid === false;
$found = $DBSH->u_count('bulk_mt_log_data', array(
'msgid' => $msgid,
));
if(!$found){
$check_valid === true;
}
$found = $DBSH->u_count('bulk_mt_log', array(
'msgid' => $msgid,));
if(!$found){
$check_valid === true;
}
}while($check_valid === false);
//
// Perform merge sms
//
$message = process_message_merge($phone_no,$user_id,$message,$company_id);
if($coding == '3'){
$len = mb_strlen($message, 'UTF-8');
$arr = array();
for( $i=0; $i<$len; $i++){
$arr[] = mb_substr($message,$i,1,'UTF-8');;
}
$message2="";
foreach($arr as $k => $substr){
$message2 .= uniord($substr);
}
$message = $message2;
}
else{
$coding = 0;
}
$data = array(
'bulk_mt_log_id' => null,
'user_id' => $user_id,
'company_id' => $company_id,
'mt_to' => $phone_no,
'campaign' => $campaign_name,
'mt_status' => 'P',
'mt_text' => $message,
'coding' => $coding,
'msgid' => $msgid,
'is_intern' => $is_intern?$is_intern:'NOT',
'per_credit' => $per_credit ? $per_credit:'0',
'mt_from' => $mt_from?$mt_from:'',
'send_c_code' => $send_c_code,
'mt_create_date' => $timestr,
'mt_update_date' => $timestr,
'ref_id' => $ref_id,
'gateway_id' => $gateway_id,
);
$DBSH->u_insert('bulk_mt_log', $data);
$rows = $DBSH->select(array(
'field' => array('*'),
'table' => 'transaction',
'where' => array(array('company_id = ?', $company_id),
array('transaction_balance > ?', 0),
array('transaction_sms_expire_date > ?', $timestr),),
'order' => 'transaction_sms_expire_date ASC',
));
$data_transaction_id = array();
while($row = $DBSH->fetchRow(DB_FETCHMODE_ASSOC)){
$data_transaction_id[] = $row[transaction_id];
}
$transaction_id = $data_transaction_id[0];
if($transaction_id){
$rows = $DBSH->update(array(
'table' => 'transaction',
'set' => array(array('transaction_balance = transaction_balance - '.$per_credit),),
'where' => array(array('company_id = ?', $company_id),
array('transaction_id = ?', $transaction_id),),
));
}
}
}
}else{
if ($phone){
foreach($phone as $k => $phone_no){
foreach($sms_message as $km => $message){
$check_credit = $credit_class->check_per_credit($phone_no,$is_intern);
$send_c_code = $check_credit['c_code' ];
$per_credit = $check_credit['per_credit'];
if($phone_no){
do{
$msgid = session_get()."_".$user_id;
$check_valid === false;
$found = $DBSH->u_count('bulk_mt_log_data', array(
'msgid' => $msgid,
));
if(!$found){
$check_valid === true;
}
$found = $DBSH->u_count('bulk_mt_log', array(
'msgid' => $msgid,));
if(!$found){
$check_valid === true;
}
}while($check_valid === false);
//
// Perform merge sms
//
$message = process_message_merge($phone_no,$user_id,$message,$company_id);
if($message_type == 'unicode'){
$coding = 3;
$len = mb_strlen($message, 'UTF-8');
$arr = array();
for( $i=0; $i<$len; $i++){
$arr[] = mb_substr($message,$i,1,'UTF-8');;
}
$message2="";
foreach($arr as $k => $substr){
$message2 .= uniord($substr);
}
$message = $message2;
}
else{
$coding = 0;
}
$data = array(
'bulk_mt_log_id' => null,
'user_id' => $user_id,
'company_id' => $company_id,
'mt_to' => $phone_no,
'campaign' => $campaign_name,
'mt_status' => 'P',
'mt_text' => $message,
'coding' => $coding,
'msgid' => $msgid,
'is_intern' => $is_intern?$is_intern:'NOT',
'per_credit' => $per_credit ? $per_credit:'0',
'send_c_code' => $send_c_code,
'mt_create_date' => $timestr,
'mt_update_date' => $timestr,
'ref_id' => $ref_id,
'mt_from' => $mt_from?$mt_from:'',
'gateway_id' => $gateway_id,
);
$DBSH->u_insert('bulk_mt_log', $data);
$rows = $DBSH->select(array(
'field' => array('*'),
'table' => 'transaction',
'where' => array(array('company_id = ?', $company_id),
array('transaction_balance > ?', 0),
array('transaction_sms_expire_date > ?', $timestr),
),
'order' => 'transaction_sms_expire_date ASC',
));
$data_transaction_id = array();
while($row = $DBSH->fetchRow(DB_FETCHMODE_ASSOC)){
$data_transaction_id[] = $row[transaction_id];
}
$transaction_id = $data_transaction_id[0];
if($transaction_id){
$rows = $DBSH->update(array(
'table' => 'transaction',
'set' => array(array('transaction_balance = transaction_balance - '.$per_credit),),
'where' => array(array('company_id = ?', $company_id),
array('transaction_id = ?', $transaction_id),),
));
}
}
}
}
}
}
}else{
$return_data['error'] = $check_credit['error'];
}
if($return_data){
$return_data['status'] ='102';
}else{
$return_data['status'] ='100';
}
return $return_data;
}
How can I edit this foreach loop so that I will be able to use strpos to look if q is found in the label ?
The result array will contain those values.
$q may be anna or ann or reas john
<?php
$q = $_GET["q"];
if (!$q) return;
$data = Array(
Array(
'label' => 'anna c13',
'category' => 'Products'
),
Array(
'label' => 'anders andersson',
'category' => 'People'
),
Array(
'label' => 'andreas johnson',
'category' => 'People'
)
);
$result = array();
foreach ($data as $value) {
array_push($result, array(
"label" => $value["label"],
"category" => $value["category"]
));
}
$json = json_encode($result);
echo $json;
?>
This will output every array in $data where $q is somewhere in 'label'.
<?php
if( !isset( $_GET["q"] )) return;
$q = $_GET["q"];
$data = Array(
Array(
'label' => 'anna c13',
'category' => 'Products'
),
Array(
'label' => 'anders andersson',
'category' => 'People'
),
Array(
'label' => 'andreas johnson',
'category' => 'People'
)
);
$result = array();
foreach ($data as $value) {
if( strpos( $value['label'], $q ) !== false ) {
$result[] = $value;
}
}
$json = json_encode($result);
echo $json;
?>
You haven't defined keys for your $data array - so it automatically take the form of:
array(
0=>array(...),
1=>array(...),
2=>array(...)
)
This means that you're using strtolower on an int - so that's probably why it's failing.
foreach ($data as $value) {
if(strpos($value['label'], $q) !== false){
$result[] = $value;
}
}