I'm trying to pull out a json feed from a Wordpress query. I need the JSON to be formatted [{"id":"1","title":"title"},{"id":"2","title":"title2"}]
The json_encode function is not pulling out this specific format: Items are not separated by commas and I'm also missing the initial and final [ ]
I made this code echoing those missing elements, which works good, but the final comma, because of the echo is making the script reading it to fail.
<?php
$args = array(
'post_type' => 'location',
'posts_per_page' => -1
);
$locations = new WP_Query($args);
if($locations -> have_posts()):
echo '[';
while ($locations->have_posts()) : $locations->the_post();
$coords = get_field('coordinates');
$pid = get_the_ID();
$json["id"] = $pid;
$json["name"] = get_the_title();
$json["lat"] = $coords['lat'];
$json["lng"] = $coords['lng'];
$json["address"] = get_field('address');
$json["address2"] = get_field('address_2');
$json["city"] = get_field('city');
$json["state"] = get_field('state');
$json["postal"] = get_field('zip_code');
$json["phone"] = get_field('office_phone');
$json["fax"] = get_field('office_fax');
$json["web"] = apply_filters('the_permalink', get_permalink());
echo json_encode($json);
echo ',';
endwhile;
echo ']';
endif;
?>
I know that echoing those elements is not the correct way to do it, and I'm doing something wrong on the encode, that's why it's pulling out without the right formatting.
I have been researching for days and I couldn't find a way to create a json_encode echoing and at the same time controlling the fields that it will show from a wordpress query.
I appreciate in advance any solution/lead to solve this.
You're adding it wrong in your loop. What you want to do is create an array, and present that array as json.
if($locations -> have_posts()):
$data = array();
while ($locations->have_posts()) : $locations->the_post();
// add the location stuff to the $data array
$data[] = array(
'id' => $pid,
'name' => get_the_title(),
// etc....
);
endwhile;
// present your json
echo json_encode($data);
endif;
Related
Looking for help in counting all values that are present in HTTP API. The link below outputs the values of multiple data points by date. What I am trying to achieve is a count on each value so that instead of
a:2:{s:10:"2018-01-03";a:9:{s:12:"nb_pageviews";d:2031;}s:10:"2018-01-04";a:9:{s:12:"nb_pageviews";d:25;}
I want to output the above nb_pageviews as a key with the value of the dates combined - 2056.
Example Link for API is https://demo.piwik.org/?module=API&method=Actions.get&idSite=7&period=day&date=last2&format=php&token_auth=anonymous
And the PHP to display this is
$url = "https://demo.piwik.org/";
$url .= "?module=API&method=Actions.get";
$url .= "&idSite=7&period=day&date=last2";
$url .= "&format=php";
$url .= "&token_auth=anonymous";
$fetched = file_get_contents($url);
$content = unserialize($fetched);
// case error
if (!$content) {
print("NO DATA");
}
foreach ($content as $row) {
$pageviews = $row['nb_pageviews'];
print("<div>$pageviews</div>\n");
}
Please note that the above link contains multiple other values that I will be wanting to do the same with, yet for ensuring the readability of this question I have kept the values simple and to just the one.
Just use the combined assignment operator, and be sure to set defaults of 0, before the loop.
$fetched = 'a:2:{s:10:"2018-01-03";a:9:{s:12:"nb_pageviews";d:2031;s:17:"nb_uniq_pageviews";d:964;s:12:"nb_downloads";d:2;s:17:"nb_uniq_downloads";d:2;s:11:"nb_outlinks";d:68;s:16:"nb_uniq_outlinks";d:64;s:11:"nb_searches";d:33;s:11:"nb_keywords";d:16;s:19:"avg_time_generation";d:0.78600000000000003;}s:10:"2018-01-04";a:9:{s:12:"nb_pageviews";d:25;s:17:"nb_uniq_pageviews";d:10;s:12:"nb_downloads";i:0;s:17:"nb_uniq_downloads";i:0;s:11:"nb_outlinks";d:1;s:16:"nb_uniq_outlinks";d:1;s:11:"nb_searches";d:2;s:11:"nb_keywords";d:2;s:19:"avg_time_generation";d:0.79300000000000004;}}';
$content = unserialize($fetched);
// case error
if (!$content) {
print("NO DATA");
}
$pageviews = 0;
$uniq_pageviews = 0;
// and on, with your other vars you're looking to sum...
foreach ($content as $row) {
$pageviews += $row['nb_pageviews'];
$uniq_pageviews += $row['nb_uniq_pageviews'];
}
var_export(['pageviews' => $pageviews, 'uniq_pageviews' => $uniq_pageviews]);
Working demo: https://eval.in/930183
// Output
array (
'pageviews' => 2056.0,
'uniq_pageviews' => 974.0,
)
To print these values, you might replace the var_export line with something like this:
$data = [
'pageviews' => $pageviews,
'uniq_pageviews' => $uniq_pageviews
];
Which you could output in some HTML like so:
<div class="col-md-4"><?php echo $data['pageviews']; ?></div>
<div class="col-md-4"><?php echo $data['uniq_pageviews']; ?></div>
This is my query and all thing going very well. problem is that only json response. when I print json .its showing only one data .while I want to list all data of current user .so please if any help then let me know Thanks .
$user1 = $wpdb->get_results(
"select product,checked_by,submit_date from diary_user_form_storage where DATE(submit_date) = CURDATE() ;
");
foreach ($user1 as $key => $value) {
$productString = stripslashes($value->product);
$checked = stripslashes($value->checked_by);
$checked_by = json_decode($checked , true);
$product = json_decode($productString, true);
$checked_by = json_decode($checked , true);
$product = json_decode($productString, true);
$date=$value->submit_date;
$date1 = date('Y-m-d',strtotime($date));
$timing= date('H:i:s',strtotime($date));
$jsonString = "";
}
header('Content-type: text/json');
echo json_encode(
array(
"status" => "1",
'user_id' => $user->ID,
'message' => 'fetched',
"token" => $token,
'token' => $token.$device_id.$device_type,
'serverUrl' => $serverUrl,
'option'=>$option,
'product' => $product,
'checked_by' =>$checked_by ,
'submit_date'=>$timing
));
?>
You misunderstand what a foreach loop is, and may be confused about variable scoping. Each time the loop loops over an element of your query, this line is executed:
$productString = stripslashes($value->product);
which overwrites the same variable over and over again. So, in the end, when you echo json_encode(/*stuff*/) only the content of the last iteration of the loop gets outputted.
Luckily for you, you can just put the echo in the loop, and each part will be outputted by your script.
Make sure to put the header before that, or your script will fail. Headers (header('Content-type: text/json');) need to be sent before actual content.
Thanks for taking a look at my question, I have developed a custom function in PHP to work with Ajax, I basically want to know if a value is in an array.
I'm checking if event_try is in the result set of a database query. In this case, 1004 is in the "$reg" array (I guarantee it), in which case the last if-else should return "notok" but I'm always getting "ok" from when I output the json with Ajax.
I've done tests with print_r and it does return "notok". It's just with the json and ajax for some reason.
Here's the code:
function validate_event_no_repeat(){
// header('Content-type: application/json');
$check_repeat_result = 0;
$check_repeat = array();
$event_try = 1004;
global $wpdb;
$current_user = wp_get_current_user();
$get_attendee = $wpdb->get_results("SELECT ATT_ID FROM su_esp_attendee_meta WHERE ATT_email='" . $current_user->user_email . "'");
foreach ($get_attendee as $atte):
$loggedID = $atte->ATT_ID;
$registration = $wpdb->get_results("SELECT ATT_ID, EVT_ID FROM su_esp_registration WHERE ATT_ID = $loggedID", ARRAY_N);
foreach ($registration as $reg):
if(in_array($event_try, $reg)):
$check_repeat[] = "notok";
else:
$check_repeat[] = "ok";
endif;
endforeach;
endforeach;
if(in_array("notok", $check_repeat)):
$check_repeat_result = "notok";
else:
$check_repeat_result = "ok";
endif;
echo json_encode(array('crr' => $check_repeat_result));
die();
}
I know the above is clearly not done by a genius but it should work shouldn't it? I would appreciate any help I could get on this.
The problem is that get_results doesn't return an array of arrays, it returns an array of objects.
You can't use in_array to check objects, so first you need to turn the object into an array - you can do this simply by casting it, e.g.
$registration = $wpdb->get_results("SELECT ATT_ID, EVT_ID FROM su_esp_registration WHERE ATT_ID = $loggedID", ARRAY_N);
foreach ($registration as $reg):
/* ADD THIS LINE: */
$reg_array = (array) $reg; /* cast the object as an array */
if(in_array($event_try, $reg_array)):
$check_repeat[] = "notok";
else:
$check_repeat[] = "ok";
endif;
endforeach;
I have an php file that gives me the response i need as a string, i need it to be an array encoded in json, im not that good with php, can any one help ?
this is how it works fine as a string
- printf("user: \"%s\" \"%s\" email: \"%s\" \n", $row['firstname'], $row['lastname'],$row['email']);
But i need it as an array in json that is how i tried to do it
-array_push($mynewArray,array("firstname \%s"=>$row['firstname'],"lastname \%s"=>$row['lastname'],"email \%s"=>$row['email']));
echo json_encode($mynewArray);
this is the screen shot that shows how i tried to do it
I think you could try like this assuming the recordset is generated correctly and available in the var $row
$mynewArray=array();
foreach($result as $row){
$mynewArray[]=$row;
}
echo json_encode($mynewArray);
Or
$mynewArray=array();
foreach( $result as $row ){
$mynewArray[]=array(
'firstname'=>$row['firstname'],
'lastname'=>$row['lastname'],
'email'=>$row['email'],
);
}
echo json_encode($mynewArray);
This might be what you're after:
<?php
$cluster = Cassandra::cluster()
->build();
$keyspace = 'msata';
$session = $cluster->connect($keyspace);
$result = $session->execute(new Cassandra\SimpleStatement
("SELECT * FROM msata.users")
);
// Create the variable array here so it's used correctly in the loop
$mynewArray = array();
foreach( $result as $row ){
// Create an array for each individual user
$user_array = array( 'firstname' => $row['firstname'], 'lastname' => $row['lastname'], 'email' => $row['lastname'] );
// Add the array to the main array
$mynewArray = array_push( $mynewArray, $user_array );
}
echo json_encode( $mynewArray );
I can't figure out what in the world is going wrong with my code.
Problem:
I'm getting results from a mysql DB, one of the variables returned needs to be run through preg_replace, the preg_replace() works just fine when I echo it out, but when I try to put that variable into the array, it doesn't reflect the preg_replace() changes.
$bl = array(
'skills' => array()
);
if ($result = $db->query($queryStmt)) {
while ($row = mysqli_fetch_assoc($result)) {
extract($row);
$newdesc = preg_replace("/\<[^>]+\)/","",$Desc);
$sk = array(
'desc' => $newdesc
);
array_push($bl['skills'], $sk);
}
};
header('Content-type: application/json');
echo json_encode($bl, JSON_NUMERIC_CHECK);
$db = NULL;
So again, if I echo the $newdesc variable before the array code, it displays properly, but when the array is echo'd out at the end of the script, it doesn't.
Edit:
Someone requested the echo response, if I echo out $newdesc this string:
MP Regeneration 3 Bow skills used at every blow mentality may be eligible for as much as 3 each additional (but does not apply to a range type)
simply echos out as this:
MP Regeneration 3 Bow skills used at every blow mentality may be eligible for as much as 3 each additional (but does not apply to a range type)
And the code now reflects this:
$bl = array(
'skills' => array()
);
if ($result = $db->query($queryStmt)) {
while ($row = mysqli_fetch_assoc($result)) {
extract($row);
$newdesc = preg_replace("/\<[^>]+\)/","",$Desc);
echo $newdesc;
$sk = array(
'desc' => $newdesc
);
array_push($bl['skills'], $sk);
}
};
header('Content-type: application/json');
echo json_encode($bl, JSON_NUMERIC_CHECK);
$db = NULL;
Edit again:
See answer for solution!
Thanks to the wonderful people in the comments, the solution to the problem was simply to use strip_tags() this my friends is a fine case of me being an idiot. Code is now this:
$bl = array(
'skills' => array()
);
if ($result = $db->query($queryStmt)) {
while ($row = mysqli_fetch_assoc($result)) {
$newdesc = strip_tags($row['Desc']);
$sk = array(
'desc' => $newdesc
);
array_push($bl['skills'], $sk);
}
};
header('Content-type: application/json');
echo json_encode($bl, JSON_NUMERIC_CHECK);
$db = NULL;
And it works perfectly.
I was making a function that already existed, read the documentation on strip_tags() for more info.
http://php.net/manual/es/function.strip-tags.php