Find value from key in JSON Array - javascript

How can i check which JSON value exist in JSON Array? Here are my solution:
var jsonArr = "[{"F_1":"c4024087","F_2":"9a565962","F_3":"23026","F_4":"John","F_5":"Doe"},{"F_1":"dbb88908","F_2":"bc6fd3bb","F_3":"19727","F_4":"Mike","F_5":"Long"}]"
Find the value:
var toFind = "9a565962";
var checkObj = jsonArr.find(o => o.F_2 == toFind );
if (typeof checkObj === "undefined") {
console.log("Value " + toFind + " not exists in Array. Do something!");
} else (Object.keys(checkObj).length > 0) {
console.log("Value " + toFind + " exists in Array. Do something else");
}
Is this the best way to find a value in a array?

$jsondata = file_get_contents("/json/API.php");
$array = json_decode($jsondata,true);
foreach($array as $k=>$val):
if($id =! $val){
echo '<b>id: '.$k.'</b></br>';
$keys = array_keys($val);
foreach($keys as $key):
echo ' '.ucfirst($key).' = '.$val[$key].'</br>';
endforeach;
endforeach;
}
Probably it will solve your problem Best Regards

Related

How to access json data in php?

I have complex json data. It can be in either formats as below :
1. {"Physics":{"5b87ceb691":"Motion","5b87ce3e":"Mass"}} //where value itself is a json
2. {"a60a8001805":"Finish chapter 1","a60a8002ab0":"Finish assignments"} //simple key value pair
I want to create checkboxes for all values (Motion, Mass, Finish chapter 1, Finish assignments for above examples) and keys should come like text in between those checkboxes (Physics for above example) (Key should come like text only if it's value is a json object, since Physics's value is a json, Physics should show like a text and in example 2, since there are no such keys whose value is a json object, no key will show like a text).
I've implemented this in javascript in the following way :
var str = "";
if(Object.keys(data).length !== 0) {
var i = 1;
for (var key in data) {
if (data.hasOwnProperty(key)) {
var val = data[key];
if(typeof val == 'object') {
str += '<div class = "data_text hidden">' + key + '</div>';
for (var subKey in val) {
if (val.hasOwnProperty(subKey)) {
var subValue = val[subKey];
str += '<div class="db-checkbox data_options hidden"><input type="checkbox" name="abc" id="' + i + '"><label for="' + i + '">' + subValue + '</label></div>'
i += 1;
}
}
} else {
str += '<div class="db-checkbox data_options hidden"><input type="checkbox" name="abc" id="' + i + '"><label for="' + i + '">' + val + '</label></div>'
i += 1;
}
}
}
Now, I want to do the same in php. I searched to find out the way to access json data in php, but all of those works only when keys are known. (For example, data->a60a8002ab0) But I want to do this generically. Don't want to hardcode anything. How can I do this? Thank you.
Try json_decode in associative mode by passing in the second param true so that it returns an associative array that you can loop through, similar to your javascript code.
//try each of the following by comment/uncomment
//$myjson = '{"Physics":{"5b87ceb691":"Motion","5b87ce3e":"Mass"}}';
//$myjson = '{"a60a8001805":"Finish chapter 1","a60a8002ab0":"Finish assignments"}';
$myjson = '{"a60a8001805":"Finish chapter 1","a60a8002ab0":"Finish assignments","Physics":{"5b87ceb691":"Motion","5b87ce3e":"Mass"}}';
$json_md_ary = json_decode($myjson,true);
$i=1;
foreach($json_md_ary as $key=>$val){
if (is_array($val)){
echo $key, "<br>";
foreach($val as $k=>$v){
echo $k, ' => ' ,$v,'<input type="checkbox" name="abc" id="'.$i.'">',"<br>";
$i++;
}
}else{
echo $key, ' => ' ,$val,'<input type="checkbox" name="abc" id="'.$i.'">',"<br>";
$i++;
}
}
$jsondata = '{"Physics":{"5b87ceb691":"Motion","5b87ce3e":"Mass"}}';
$data = json_decode($jsondata);
foreach($data as $key => $val){
print_r($val);
}

objects, php, javascript errors

Javascript Object to a PHP Object
I was searching for the tutorial how to pass associative array from JavaScript to PHP object and found this video. I think it is a little bit old it was added in 2010. I tried it and had error. I ask you to help me to correct it or help me to to get php object from js object.
index.php
<script>
let ar = new Array();
ar["name"] = "name1";
ar["name1"] = "name2";
console.log(ar);
function convertOb(object){
var json = "{";
for (property in object) {
var value = object[property];
if (typeof(value) == "string") {
json += '"' + property + '":"' + value +'",';
} else{
if (!value[0]) {
json += '"' + property + '":"' + convertOb(value) + ',';
} else{
json+= '"'+ property +'":[';
for (prop in value) json+= '"' + value[prop] + '",';
json = json.substr(0,json.length-1) + "],";
}
}
} return json.substr(0,json.length-1) + "}";
}
let json = convertOb(ar);
$.post("main.php", {json:json}, function(data){
console.log(data);
});
</script>
main.php
<?php
function jsonstring2obj($str){
return json_decode(stripslashes($str));
}
$ar = jsonstring2obj($_POST['json']); //error1
echo $ar->name; //error2
?>
My errors:
Undefined index: json //error1
Trying to get property 'name' of non-object //error2

How to add data from database into object in php for temporary using while loading

I am new in php . I have the following code to retrieve categorytype data from database?. I want to add them into php object for temporary using while loading page. First, I want to load all predefined data, then i will use it when i click function. Could you enlighten me how to create it
categoryDao.php
namespace category;
use Exception;
use PDO;
class categoryDao{
public function categorytype(PDO $connection){
$conn = $connection;
try {
$conn = $connection;
$sql="SELECT * FROM `tb_category` WHERE id != parent_id;";
$categorytype = $conn->prepare($sql);
$categorytype->execute();
$data1 = array();
while (
$result = $categorytype->fetch(PDO::FETCH_ASSOC)) {
$data1[] = $result['id'];
$data1[] = $result['c_name'];
}
return $data1;
} catch (Exception $e) {
echo $e;
throw $e;
}
}
}
categoryservice.php
use category\categoryDao;
require '../dao/categoryDao.php';
require 'Dao.php';
class categoryService{
public function categorytype(){
$dao = new Dao();
$conn= $dao->connect();
$conn->beginTransaction();
$categoryDao = new categoryDao();
//$data1 = array();
$data1=$categoryDao->categorytype($conn);
return $data1;
$dao->disconnect($conn);
}
}
categorytypecontroller.php
<?php
require '../service/categoryService.php';
require '../service/categoryService.php';
$categoryname = #trim(stripslashes($_POST['category']));
$category = new categoryService();
//$ctype = array();
$ctype = $category->categorytype();
$return["json"] = json_encode($ctype);
echo $return["json"];
Head.php
function categorytype() {
//var hosname =window.location.protocol + "//" + window.location.hostname + window.location.pathname;
var hosname1 = window.location.protocol + "//" + window.location.hostname+ "/servicegateway/sgw/modules/controller/categorytypecontroller.php";
alert (hosname1);
//var ur = hosname + "/modules/controller/categorycontroller.php";
$.ajax({
url:hosname1 , //the page containing php script
type: "POST", //request type,
dataType: 'json',
data: '',
success:function(data1){
alert(data1);
var obj =data1;
// var leng = Object.keys(obj).length;
var areaOption = "<option value=''>Select Category </option>";
for (var i = 0; i < obj.length; i++) {
areaOption += '<option value="' + obj[i] + '">' + obj[i] + '</option>'
}
$("#c_type").html(areaOption);
}
});
}
A couple of things. If you want the data to be an array of records, you'll probably want to change this part:
while ($result = $categorytype->fetch(PDO::FETCH_ASSOC)) {
$data1[] = $result['id'];
$data1[] = $result['c_name'];
}
as that is putting all the fields, one after the other, into a normal array.
while ($result = $categorytype->fetch(PDO::FETCH_ASSOC)) {
$data1[] = array(
'id' => $result['id'],
'c_name' => $result['c_name']
);
}
That will create a small associative array of the id and name fields and put it into another array, with the other records. PHP associative arrays will turn into Javascript objects when sent via ajax.
Then, in Javascript, you'll want to make use of those objects to create your options, so:
areaOption += '<option value="' + obj[i].id + '">' + obj[i].c_name + '</option>'

How to get PHP array results using JQuery

Below are a couple of queries that ultimately build an array.
if(isset($_POST['getarray'])){
try{
$ret = array();
$stmt = $db->prepare('SELECT groupdate, groupid
FROM participationtemp
WHERE memberid = :memberid
AND groupid = :groupid
ORDER BY groupdate, groupid DESC');
$stmt->bindValue(':groupid', $_POST['groupid'], PDO::PARAM_INT);
$stmt->bindValue(':memberid', $_SESSION['memberid'], PDO::PARAM_INT);
$stmt->execute();
$result = $stmt->fetchAll();
foreach($result as $row){
$attenddate = $row[0];
$stmt = $db->prepare('SELECT h.clientid, attend, attend_date
FROM history AS h
INNER JOIN suspended AS s on s.clientid = h.clientid
WHERE h.memberid = :memberid
AND h.groupid = :groupid
AND attend_date = :attenddate
AND suspend = "N"');
$stmt->bindValue(':memberid', $_SESSION["memberid"], PDO::PARAM_INT);
$stmt->bindValue(':groupid', $_POST['groupid'], PDO::PARAM_INT);
$stmt->bindValue(':attenddate', $attenddate, PDO::PARAM_STR);
$stmt->execute();
$result = $stmt->fetchAll();
foreach($result as $row ) {
array_push($ret, ['id' => $row[0], 'gdate' => $row[2]]);
}
}
echo json_encode($ret);
exit();
} catch (PDOException $ex){
mail_error($ex);
}
}
After returning to JQuery, alert(re); shows I successfully created the array.
success:function(re){
alert(re);
But I'm having trouble accessing the array data. Without success, this is what i've tried:
data = $.parseJSON(re);
$.each(data, function(i, val) {
alert(i + "=" + val);
});
and this:
data = $.parseJSON(re);
$.each(data, function(i, val) {
if(i == "id"){
alert(i + "=" + val);
}
if(i == "gdate"){
alert(i + "=" + val);
}
});
I've also tried dot notation.
$.each(re.id, function(i, val) {
alert(i + "=" + val);
}
});
$.each(re.gdate, function(i, val) {
alert(i + "=" + val);
});
I've never used JSON before and don't understand why I can't retrieve the array data. Any help will be appreciated. Thanks.
The following code checks whether re is a string, or an object. The latter is possible if jQuery.ajax() method is used with "json" dataType. Also, jQuery is capable of parsing JSON automatically, if the response MIME type is application/json (the Content-Type HTTP header), particularly. So it is a good idea to check if re has been parsed by jQuery.
var d = typeof re === 'string' ? JSON.parse(re) : re;
var i;
for (i = 0; i < d.length; i++) {
console.log("id = ", d[i].id,
"gdate = ", d[i].gdate);
}
I'd recommend returning the appropriate content type from PHP:
header ('Content-Type: application/json');
echo json_encode($ret);
exit();
$.each(re, function(i, val) {
alert(val.id + "=" + val.gdate);
});
Try this code :)
// Json in string format
var jsonString = '[{"id":"1", "gdate":"2016-10-13"},{"id":"2", "gdate":"2016-10-13"},{"id":"3", "gdate":"2016-10-13"},{"id":"4", "gdate":"2016-10-13"},{"id":"5", "gdate":"2016-10-13"},{"id":"6", "gdate":"2016-10-13"}]';
// Convert string to json object
var json = JSON.parse(jsonString);
// Iterate over json object
jQuery.each(json, function(index, value) {
console.log(index, value);
});
// Simple access to attribute in json object
console.log('json[1][\'id\'] = ', json[1]['id']);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

javascript encode uri and arrays/objects

I'm trying to write a function that will run encodeURIComponent on arrays or objects regardless of the depth. It all seems to go well until I return the final result.
<script src="https://code.jquery.com/jquery-3.1.0.min.js" integrity="sha256-cCueBR6CsyA4/9szpPfrX3s49M9vUU5BgtiJj06wt/s=" crossorigin="anonymous"></script>
<script>
function encodeURI_array($Array) {
$Result = [];
if($Array !== null && typeof $Array === 'object') {
//for(var key in $Array) {
Object.keys($Array).forEach(function (key) {
if($Array[key] !== null && typeof $Array[key] === 'object') {
console.log("encode array: " + key + " : " + $Array[key]);
$Result[key] = encodeURI_array($Array[key]);
} else {
$Result[key] = encodeURIComponent($Array[key],"UTF-8").replace(/\+/g, ' ').replace("%26","&").replace("%2C",",");
console.log("encode strings: " + key + " : " + $Result[key]);
}
});
console.log("Final result");
console.log($Result);
return $Result;
} else {
$Result = encodeURIComponent($Array,"UTF-8").replace(/\+/g, ' ').replace("%26","&").replace("%2C",",");
console.log("encode string: " + $Result);
return $Result;
}
}
$TestArray = [{"Key1":"Value1"},{"Key2":"Value2"},{"Key3":"Value3"}];
$TestArray2 = {"Key":"Value"};
(encodeURI_array($TestArray));
//console.log(encodeURI_array($TestArray2));
</script>
For this script, the very last result returns only the last object in the array when it should be returning an array of objects.

Categories