I'm having problems looking through the array data from a json file.
This is the code I have
$barcode = '0000000' //just an example this is set as a variable
$json_data = json_decode($json,true);
foreach ($json_data as $data){
$barcodejson = $data['Barcode'];
if($barcodejson == $barcode){
$alreadyscanned = 'This user is already in your contacts';
} else { do something}
}
The problem I have is its only 'looking' at the last set of data and not all of it. if I put the barcode in twice I get the error This user is already in your contacts but if I put a new one in and then the existing barcode again it doesn't work.
I'm sure its something to do with the foreach loop but can not figure it out.
my json data is structured like this :
[
{
"FirstName": "lee",
"LastName": "skelding",
"Email": "mail.mail.com",
"Barcode": "732580652913857773001",
"Phone": "00000000",
"Company": "SKELLATECH V3",
"Position": "CEO"
},
{
"FirstName": "Kenneth",
"LastName": "Brandon",
"Email": "mail.mail.com",
"Barcode": "732559813913833509001",
"Phone": null,
"Company": null,
"Position": null
},
{
"FirstName": "lee",
"LastName": "skelding",
"Email": "mail.mail.com",
"Barcode": "732580652913857773001",
"Phone": "0000000000",
"Company": "SKELLATECH V3",
"Position": "CEO"
}
]
what I want to do is see if the barcode number already exists in the json file if it does show the error if it doesn't carry on with the rest of my code and add in the new data
For the second iteration, the $alreadyscanned will be set on a user that doesn't match the condition if one that has been scanned already came before it. Either reset the value of $alreadyscanned or use array to keep a list of errors.
$alreadyscanned = [];
foreach ($json_data as $data){
$barcodejson = $data['Barcode'];
if($barcodejson == $barcode){
$alreadyscanned[$barcodejson] = 'This user is already in your contacts';
} else { do something}
}
foreach($alreadyscanned as $barcode => $error) {
var_dump($barcode. " :: " . $error);
}
Consider using break in your loop when you get into the if part: you don't want to continue once you find a duplicate:
if($barcodejson == $barcode){
$alreadyscanned = 'This user is already in your contacts';
break;
} else { do something}
Now the dosomething could be unwanted here (depending on what it does). You may need to do that in a separate loop. Something like this:
$alreadyscanned= "";
foreach ($json_data as $data){
$barcodejson = $data['Barcode'];
if($barcodejson == $barcode){
$alreadyscanned = 'This user is already in your contacts';
break;
}
}
if ($alreadyscanned=="") {
foreach ($json_data as $data){
$barcodejson = $data['Barcode'];
// do something
}
}
Lacking semicolons and stuff makes it harder to get the desired result.
Something like this might help you out on getting the data you want. Basically you can check the result of parsing by print_r-ing the json decoding process.
Then, you get a process result for each entry and, again, as a test, you can print the resulting array.
<?php
//Enter your code here, enjoy!
$json = '[
{
"FirstName": "lee",
"LastName": "skelding",
"Email": "mail.mail.com",
"Barcode": "732580652913857773001",
"Phone": "00000000",
"Company": "SKELLATECH V3",
"Position": "CEO"
},
{
"FirstName": "Kenneth",
"LastName": "Brandon",
"Email": "mail.mail.com",
"Barcode": "732559813913833509001",
"Phone": null,
"Company": null,
"Position": null
},
{
"FirstName": "lee",
"LastName": "skelding",
"Email": "mail.mail.com",
"Barcode": "732580652913857773001",
"Phone": "0000000000",
"Company": "SKELLATECH V3",
"Position": "CEO"
}]'
;
$barcode = '732580652913857773001'; //just an example this is set as a variable
$json_data = json_decode($json, true);
print_r($json_data);
foreach ($json_data as $data){
$barcodejson = $data['Barcode'];
if($barcodejson == $barcode){
$alreadyscanned[] = 'user ' . $data["Email"] .' is already in your contacts';
} else {
$alreadyscanned[] = 'This user '. $data["Email"] .' is not in your contacts';
}
}
print_r($alreadyscanned);
You need to use a function for that, so that you can use return when you find the needed barcode
function searchbarcode($json_data, $barcode)
{
foreach($json_data as $data)
{
if ( $data['Barcode'] == $barcode )
return true;
}
return false;
}
$barcode = '0000000' //just an example this is set as a variable
$json_data = json_decode($json,true);
if(searchbarcode($json_data, $barcode)){
$alreadyscanned = 'This user is already in your contacts';
} else { do something}
Related
How can I output this json to csv properly?
My json file pattern is like this:
{
"swimmers": [
{
"Province": "Ontario",
"Exemption": "S9,SB9,SM9",
"Code": "A,3,4",
"Level": "Level 8",
"ClassificationDate": "2020",
"RYEar": "2024",
"Status": "Registered",
"ID": "123456",
"FirstName": "John",
"LastName": "Doe",
"Gender": "M",
"AGE": null,
"DOB": "01/11/2000",
"Clubs": [
{
"Clubname": "Human Fish",
"Code": "ABC",
"Clubid": "300"
}
],
"Email": null,
"Language": "E",
"ChallengeData": null
}
//more entries with same pattern as first
],
"status": "OK",
"application": "SOme App API"
}
I had success to turn it into a csv with the code below but I'm unable to output the clubs field in the csv file, instead of showing the club, it just shows "Array()". I tried to fix that with the commented code but it doesn't solve the problem.
$csvFileName = 'converted.csv';
$json = 'myjson.json';
$data = file_get_contents($json);
$payload= json_decode($data);
$file_pointer = fopen($csvFileName, 'w');
if ($file_pointer){
foreach($payload['swimmers'] as $row) {
// $clubs = $row['Clubs'] ;
// if (is_array($clubs)){
// foreach($clubs as $c){
// fputcsv($file_pointer, $c);
// }
// }else{
fputcsv($file_pointer, $row);
}
}
Append each element of the Clubs field to $row, then remove the Clubs field.
foreach ($payload['swimmers'] as $row) {
foreach ($row['Clubs'] as $club) {
$row = array_merge($row, array_values($club));
}
unset($row['Clubs']);
fputcsv($file_pointer, $row);
}
This is the JSON
{
"circuit_list": [
{
"_id": "58c0f378a986f808cdaf94cf",
"aggregation": {
"dev_name": "ME2-D2-BOO",
"port": {
"desc": "AKSES_SITE_SITE-TSEL_ME2-D2-BOO#1/2/5_200M_BOO082#CIPAKUBOO534",
"name": "1/2/5"
}
},
"area": "AREA 2",
"site_id": "N/A",
"site_name": "N/A"
},
{
"_id": "58c0f378a986f808cdaf94d0",
"aggregation": {
"dev_name": "ME2-D2-BOO",
"port": {
"desc": "AKSES_SITE_SITE-TSEL_ME2-D2-BOO#1/2/5_200M_BOO082#CIPAKUBOO534",
"name": "1/2/5"
}
},
"area": "AREA 2",
"site_id": "N/A",
"site_name": "N/A"
}
}
I already try with this code
$json = json_decode($url, true);
foreach($json as $value)
{
$_id = $value->_id;
}
it didn't work. Please help, I need to get the value to show them on the view. Did I do this wrong? this json is difficult because i didn't understand the structure.
I usually decode json with format
[{"id":"1","name":"faisal"}]
like this and with my foreach it's working.
If the second parameter of json_decode is true, the function will return an array instead of an object. Also, you would need to loop over the circuit_list property of the object.
$json = json_decode($url); // <- remove the parameter
foreach($json->circuit_list as $value) // <- loop over circuit_list
{
$_id = $value->_id;
}
<?php
$json = json_decode($url,true);
foreach($json['circuit_list'] as $value)
{
$id = $value['_id'];
}
?>
I am using slimphp v2 and I have the following function
function gt($user) {
$sql = "select id, id as categoryId, mobile, task from actions where status=0";
try {
$db = newDB($user);
$stmt = $db - > prepare($sql);
$stmt - > execute();
$gs = $stmt - > fetchAll(PDO::FETCH_OBJ);
if ($gs) {
$db = null;
echo json_encode($gs, JSON_UNESCAPED_UNICODE);
} else {
echo "Not Found";
}
} catch (PDOException $e) {
echo '{"error":{"text":'.$e - > getMessage().
'}}';
}
}
The default json output looks like:
[{
"id": "1",
"categoryId": "1",
"mobile": "111",
"task": "test"
},
{
"id": "2",
"categoryId": "2",
"mobile": "222",
"task": "test2"
}]
and the output that i am trying to make. I need to generate an ID: 1_(id) then format it like this
[{
id: "1",
task: "test",
}, {
ID: "1_1", //generate this, add 1_id
categoryId: "1",
mobile: "00000",
}, {
id: "2",
task: "test2",
}, {
ID: "1_2", //generate this, add 1_id
categoryId: "2",
mobile: "11111"
}];
Is it possible?
Thanks
I'm not sure if this is exactly what your after but you can gain the desired JSON output by converting your original JSON into an associative array and then restructure the data on each iteration using a Foreach() loop into a new assoc array. After that, you can just convert it back to JSON using json_encode().
Code:
$json = '[{
"id": "1",
"categoryId": "1",
"mobile": "111",
"task": "test"
},
{
"id": "2",
"categoryId": "2",
"mobile": "222",
"task": "test2"
}]';
$jsonArr = json_decode($json, TRUE);
$newArr = [];
foreach ($jsonArr as $v) {
$newArr[] = ['id:'=>$v['id'], 'task:' => $v['task']];
$newArr[] = ['ID:'=>'1_' . $v['id'], 'categoryId' => $v['categoryId'], 'mobile'=>$v['mobile']];
}
$newJson = json_encode($newArr);
var_dump($newJson);
Output:
[{
"id:": "1",
"task:": "test"
}, {
"ID:": "1_1",
"categoryId": "1",
"mobile": "111"
}, {
"id:": "2",
"task:": "test2"
}, {
"ID:": "1_2",
"categoryId": "2",
"mobile": "222"
}]
Edit -- Updated Answer
As discussed in comments, your outputting your SQL array as an object. I've set the Fetch to output as an associative array using PDO::FETCH_ASSOC and changed the foreach() loop to reference the assoc array $gs. This should work but if not then output your results for $gs again using var_dump($gs). You will still need to encode to JSON if needed but this line has been commented out.
function gt($user) {
$sql = "select id, id as categoryId, mobile, task from actions where status=0";
try {
$db = newDB($user);
$stmt = $db->prepare($sql);
$stmt->execute();
$gs = $stmt->fetchAll(PDO::FETCH_ASSOC); //Fetch as Associative Array
if ($gs) {
$db = null;
$newArr = [];
foreach ($gs as $v) { //$gs Array should still work with foreach loop
$newArr[] = ['id:'=>$v['id'], 'task:' => $v['task']];
$newArr[] = ['ID:'=>'1_' . $v['id'], 'categoryId' => $v['categoryId'], 'mobile'=>$v['mobile']];
}
//$newJson = json_encode($newArr); //JSON encode here if you want it converted to JSON.
} else {
echo "Not Found";
}
} catch(PDOException $e) {
//error_log($e->getMessage(), 3, '/var/tmp/php.log');
echo '{"error":{"text":'. $e->getMessage() .'}}';
}
}
I am trying to decode JSON data to PHP then output it to the site. If I have the following:
{
"name": "josh",
"type": "human"
{
I can do this (within PHP), to display or output my type:
$file = "path";
$json = json_decode($file);
echo $json["type"]; //human
So, if I have the following:
{
"name": "josh",
"type": "human",
"friends": [
{
"name": "ben",
"type": "robot"
},
{
"name": "tom",
"type": "alien"
}
],
"img": "img/path"
}
How can I output what type my friend ben is?
Use a loop like foreach and do something like the following:
//specify the name of the friend like this:
$name = "ben";
$friends = $json["friends"];
//loop through the array of friends;
foreach($friends as $friend) {
if ($friend["name"] == $name) echo $friend["type"];
}
To get the decoded data in array format you would supply true as the second argument to json_decode otherwise it will use the default which is object notation. You could easily create a function to shorten the process when you need to find a specific user
$data='{
"name": "josh",
"type": "human",
"friends": [
{
"name": "ben",
"type": "robot"
},
{
"name": "tom",
"type": "alien"
}
],
"img": "img/path"
}';
$json=json_decode($data);
$friends=$json->friends;
foreach( $friends as $friend ){
if( $friend->name=='ben' )echo $friend->type;
}
function finduser($obj,$name){
foreach( $obj as $friend ){
if( $friend->name==$name )return $friend->type;
}
}
echo 'Tom is a '.finduser($friends,'tom');
try this,
$friend_name = "ben";
$json=json_decode($data);
$friends=$json->friends;
foreach( $friends as $val){
if($friend_name == $val->name)
{
echo "name = ".$val->name;
echo "type = ".$val->type;
}
}
DEMO
I am trying to create a search a function in php which searches for the data contained inside a Json file. I am able to do this for a normal text file which returns a list of results based on what has been entered in the search field which returns closet match. However does not work when doing this same for a json file and does not return anything.
search.php
if (isset($_POST) && isset($_POST['txt'])) {
$search = $_POST['txt'];
$file = file('data/contacts.json');
$found = false;
$jsonData = json_decode($file, true);
foreach ($jsonData as $line) {
if (strpos($line, $search) !== false) {
$found = true;
echo $line;
}
}
if (!$found) {
echo 'No match found';
}
}
contacts.json
[
{
"id": 3,
"forename": "John",
"surname": "Smith",
"email": "j#hotmail.com",
"address": "addresss",
"telephone": "01232302323"
},
{
"id": 4,
"forename": "Keith",
"surname": "Miller",
"email": "K#hotmail.com",
"address": "ssdsds",
"telephone": "01232302323"
},
{
"id": 5,
"forename": "Doug",
"surname": "Howard",
"email": "d#hotmail.com",
"address": "test",
"telephone": "01232302323"
},
{
"id": 2,
"forename": "r",
"surname": "r",
"email": "email#gmail.com",
"address": "test",
"telephone": "01232302323"
}
]
Change this line $jsonData = json_decode($file, true); to
$jsonData = json_decode(json_encode($file),true);