I'm trying to receive the data from JSON with PHP and use it in my SELECT query. I have searched everywhere and every solution didn't worked for me.
My Returned JSON data:
"{processos:[{"processo":"203"},{"processo":"1430"}]}"
My PHP:
$ar2 = json_decode($processo2, true);
$where2 = array();
foreach($ar2['processo'] as $key=>$val){
$where2[] = $val;
}
$where2 = implode(',', $where2);
$pegaSonda = $pdo->prepare("SELECT * FROM sonda WHERE n_processo IN ($where2)");
$pegaSonda->execute();
What's wrong with my code?
EDIT
The code from #wadersgroup worked correctly, but when i change to my variable it stops. This is the way i'm encoding it:
$jsonData = array();
$jsonData[] = array("processo" => $automovel->n_processo);
$data['processo2'] .= '{"processos":'.json_encode($jsonData).'}';
$data['processo2'] is sending to my AJAX to populate the input and then it receive data back with:
$processo2 = strip_tags(stripslashes($_POST['n_processo2']));
There are many errors in this code. Try this
$ar2 = json_decode('{"processos":[{"processo":"203"},{"processo":"1430"}]}', true);
$where2 = array();
foreach($ar2['processos'] as $key=>$val){
$where2[] = $val['processo'];
}
$where = implode(',', $where2);
print_r($where);
Your JSON string looks invalid, try instead:
'{"processos":[{"processo":"203"},{"processo":"1430"}]}'
$processo2 = '{"processos": [{ "processo": "203"},{ "processo": "1430"}]}'
$ar2 = json_decode($processo2, true);
$arr = array_map(function($i) {return $i['processo']; }, $ar2["processos"]);
$where = implode(", ", $arr);
Related
I want to get the imdb_id from inside json using foreach
i am having an issue with getting it decoded and displayed.
My php code so far:
$themoviedburl = "http://api.themoviedb.org/3/tv/60625/external_ids?api_key=";
$get = file_get_contents($themoviedburl);
$decode1 = json_decode($get, TRUE);
foreach($decode1['external_ids'] as $value){
$imdb = $value['imdb_id'];
}
Json:
{"id":60625,"imdb_id":"tt2861424","freebase_mid":"/m/0z6p24j","freebase_id":null,"tvdb_id":275274,"tvrage_id":33381,"facebook_id":"RickandMorty","instagram_id":"rickandmorty","twitter_id":"RickandMorty"}
After $decode1 = json_decode($get, TRUE);
You can simply do $imdb_ids = array_column($decode1['external_ids'],'imdb_id'); to collect all imdb_id in one array.
More info on array_column : https://www.php.net/manual/en/function.array-column.php
As discussed in the comments, to get only one imdb_id ID, you can do like below:
$json = '{"id":60625,"imdb_id":"tt2861424","freebase_mid":"/m/0z6p24j","freebase_id":null,"tvdb_id":275274,"tvrage_id":33381,"facebook_id":"RickandMorty","instagram_id":"rickandmorty","twitter_id":"RickandMorty"}';
$decoded_data = json_decode($json,true);
$imdb_id = $decoded_data['imdb_id'];
I need looped php data in an html template so I know it has something to do with JSON however not a JSON expert and cannot find much help in searching the web.
$uniqueFranchise_id = array_unique($franchise_id);
$dataArr = '[
{
"name": "Dylan",
"page_link": "https://mypage.com/"
}
]';
foreach($uniqueFranchise_id as $franchise)
{
$sqlFranchise = "select * from franchise where franchise_id = $franchise";
$resultFranchise = $conn->query($sqlFranchise);
if($resultFranchise->num_rows > 0)
{
while($rowFranchise = $resultFranchise->fetch_assoc())
{
$dataArr = json_decode($data, TRUE);
$dataArr[] = "['name'=>'".$rowFranchise['name']."', 'page_link'=>'".$rowFranchise['page_link']."']";
//$json = json_encode($dataArr);
}
}
}
$json = json_encode($dataArr);
print_r($dataArr);
But it only appends one row. In fact it deleteds that data that's already in my dataArr and just adds one row from my loop? Maybe I'm approaching this situation completely wrong?
You set your $dataArr inside the while-loop. So each time the loop is runs, it will be overwritten. Also, it makes more sense and it's much more clear when you handle it as an array (or object) and afterwards convert it to JSON.
$dataArr = array(array('name' => 'Dylan', 'page_link' => 'https://mypage.com/'));
foreach($uniqueFranchise_id as $franchise)
{
$sqlFranchise = "select * from franchise where franchise_id = $franchise";
$resultFranchise = $conn->query($sqlFranchise);
if($resultFranchise->num_rows > 0)
{
while($rowFranchise = $resultFranchise->fetch_assoc())
{
$dataArr[] = array('name' => $rowFranchise['name'], 'page_link' => $rowFranchise['page_link']);
}
}
}
$json = json_encode($dataArr);
echo $json;
You shouldn't be building the string up by yourself, you should build the data and then JSON encode the result (comments in code)...
$dataArr = '[
{
"name": "Dylan",
"page_link": "https://mypage.com/"
}
]';
// decode existing JSON to start array
$dataArr = json_decode($data, TRUE);
foreach($uniqueFranchise_id as $franchise)
{
// Read just the data you need from the table
$sqlFranchise = "select name, page_link from franchise where franchise_id = $franchise";
$resultFranchise = $conn->query($sqlFranchise);
if($resultFranchise->num_rows > 0)
{
// Read all of the rows into an array
$newData = $resultFranchise->fetch_all(MYSQLI_ASSOC);
// Add in existing data
$dataArr = array_merge($dataArr, $newData);
}
}
// Now encode the list of elements into 1 string
echo json_encode($dataArr);
You should also look into prepared statements if this data is not trusted to stop SQL injection.
Probably a stupid question here, I apologize...
I have a SQL request into a foreach, like below.
The "auth" string is correctly defined, a "echo $auth" returns what I want. But the sql request returns nothing.
// $auth=something;
$val=array(value1,value2,value3);
foreach ($val as $j)
{
$req = mysqli_fetch_array(mysqli_query($link,"select val from user where auth='$auth'"));
$$j=$req[val];
}
My goal is to select the sql fieds contained in the $val array (it perfectly works in others parts of my project). Thanks in advance.
I also tried this, still does not return anything :
$val = array('mail','preferences','info','langue'); // This must be an array
$fields = explode(",", $val);
$req = mysqli_fetch_array(mysqli_query($link,"select $fields from user where auth='$auth'"));
$mail = $req[0]; $preferences = $req[1]; $info = $req[2]; $info = $req[3];
My goal is to select the sql fieds contained in the $val array
So the $val contains the fields you want to use on your query. You can use an explode() to retrieve all the fields without a foreach:
$fields = explode(",", $val);
$req = mysqli_fetch_array(mysqli_query($link,"select $fields from user where auth='$auth'"));
And the you can get the value:
$value1 = $req[$val[0]]; // First field
Okay, let's resume all that. so we have two methods. First :
$val=array(mail,preferences,info,langue);
foreach ($val as $j)
{
$auth = $_SESSION['auth'];
echo $auth; //this works
$req = "select val from user where auth='$auth'";//this works only in phpMyadmin
$req = mysqli_fetch_array(mysqli_query($link,$req));
$$j=$req[val];
}
echo $mail; //gives nothing of course...
And here's the second one :
val = array('mail','preferences','info','langue');
$fields = explode(",", $val);
$req = mysqli_fetch_array(mysqli_query($link,"select $fields from user where auth='$auth'"));
$mail = $req[$val[0]]; $preferences = $req[$val[1]]; $info = $req[$val[2]]; $info = $req[$val[3]];
Still nothing works. No php problem detected, my Mysqli instances work correctly... PLEASE do notice we are in debug mode, so my first code is not optimized of course...
The problem is the use of explode which splits a string on a delimiter and create an array. You already have an array, but you want to make it a string. To do this you can use implode:
$columns = array("mail", "preferences", "info", "language");
$sql = sprintf("SELECT %s FROM user WHERE auth='%s'", implode(",", $columns), $auth);
$query = mysqli_query($sql); //..fetch possible errors
$row = mysqli_fetch_array($query); //..make sure a row was returned
list($mail, $preferences, $info, $language) = $row;
echo $mail;
I have two json's
First one is
[{"COLUMN_NAME":"ORDER_NO","COLUMN_TITLE":"Order Number"}
,{"COLUMN_NAME":"CUSTOMER_NO","COLUMN_TITLE":"Customer Number"}]
Second one is
[{"COLUMN_NAME":"ORDER_NO","DEFAULT_VALUE":"1521"},
{"COLUMN_NAME":"CUSTOMER_NO","DEFAULT_VALUEE":"C1435"}]
I want to merge them and have a json like
[{"COLUMN_NAME":"ORDER_NO","COLUMN_TITLE":"Order Number","DEFAULT_VALUE":"1521"}
,{"COLUMN_NAME":"CUSTOMER_NO","COLUMN_TITLE":"Customer Number","DEFAULT_VALUEE":"C1435"}]
is there a way to merge them? It is also OK for me if a stucture change in JSON is required
thanks.
Something like this should work:
json_encode(
array_merge(
json_decode($a, true),
json_decode($b, true)
)
)
or the same as one-liner:
json_encode(array_merge(json_decode($a, true),json_decode($b, true)))
array_merge in official PHP documentation
json_decode in official PHP documentation
EDIT: try adding true as second parameter to json_decode. That'll convert objects to associative arrays.
EDIT 2: try array-merge-recursive and see my comment below. Sorry have to log out now :(
This looks like a full correct solution: https://stackoverflow.com/a/20286594/1466341
Managed to throw this together. There is most likely a better solution, but this is the closest I got.
$a = '[{"COLUMN_NAME":"ORDER_NO","COLUMN_TITLE":"Order Number"},{"COLUMN_NAME":"CUSTOMER_NO","COLUMN_TITLE":"Customer Number"}]';
$b = '[{"COLUMN_NAME":"ORDER_NO","DEFAULT_VALUE":"1521"},{"COLUMN_NAME":"CUSTOMER_NO","DEFAULT_VALUEE":"C1435"}]';
$r = [];
foreach(json_decode($a, true) as $key => $array){
$r[$key] = array_merge(json_decode($b, true)[$key],$array);
}
echo json_encode($r);
returns,
[{"COLUMN_NAME":"ORDER_NO","DEFAULT_VALUE":"1521","COLUMN_TITLE":"Order Number"},
{"COLUMN_NAME":"CUSTOMER_NO","DEFAULT_VALUEE":"C1435","COLUMN_TITLE":"Customer Number"}]
This works like a charm for me
json_encode(array_merge(json_decode($a, true),json_decode($b, true)))
here is a full example
$query="SELECT * FROM `customer` where patient_id='1111118'";
$mysql_result = mysql_query($query);
$rows = array();
while($r = mysql_fetch_assoc($mysql_result)) {
$rows[] = $r;
}
$json_personal_information=json_encode($rows);
//echo $json_personal_information;
$query="SELECT * FROM `doctor` where patient_id='1111118'";
$mysql_result = mysql_query($query);
$rows = array();
while($r = mysql_fetch_assoc($mysql_result)) {
$rows[] = $r;
}
$json_doctor_information=json_encode($rows);
//echo $json_doctor_information;
echo $merger=json_encode(array_merge(json_decode($json_personal_information, true),json_decode($json_doctor_information, true)));
This worked to me!
$dados1 = json_encode(array('data'=>'1'));
$dados2 = json_encode(array('data2'=>'2'));
echo json_encode(array_merge(json_decode($dados1, true),json_decode($dados2, true)));
I am attempting to fetch JSON from Instagram according to a number of URL parameters, the JSON is then decoded and then the objects required are then encoded into my own JSON format. Whilst I know this sound a little ridiculous, it is what is required. My only issue here is that for some reason it does not encode each section of JSON, it will only work for one item. The code is as below.
<?php
function instagram($count=16){
$igtoken = $_GET['igtoken'];
$hashtag = $_GET['hashtag'];
$url = 'https://api.instagram.com/v1/tags/'.$hashtag.'/media/recent/?access_token='.$igtoken.'&count='.$count;
$jsonData = json_decode((file_get_contents($url)));
$jsonData = json_decode((file_get_contents($url)));
foreach ($jsonData->data as $key=>$value) {
$response = array();
$response["data"] = array();
$data = array();
$data["createdtime"] = $value->caption->created_time;
$data["username"] = $value->caption->from->username;
$data["profileimage"] = $value->caption->from->profile_picture;
$data["caption"] = $value->caption->text;
$data["postimage"] = $value->images->standard_resolution->url;
array_push($response["data"], $data);
$result = json_encode($response);
}
return $result;
}
echo instagram();
?>
It will work for each section of JSON if I do something like this instead:
$result .= '<li>
'.$value->caption->from->username.'<br/>
'.$value->caption->from->profile_picture.'<br/>
'.$value->caption->text.'<br/>
'.$value->images->standard_resolution->url.'<br/>
'.$value->caption->created_time.'<br/>
</li>';
I feel I have bodged up somewhere with the array, however i'm not entirely sure.
What if we move $response["data"] and $result varia out of foreach?
Have you tried this?
$response = array();
$response["data"] = array();
foreach ($jsonData->data as $key=>$value) {
$data = array();
$data["createdtime"] = $value->caption->created_time;
$data["username"] = $value->caption->from->username;
$data["profileimage"] = $value->caption->from->profile_picture;
$data["caption"] = $value->caption->text;
$data["postimage"] = $value->images->standard_resolution->url;
array_push($response["data"], $data);
}
$result = json_encode($response);
return $result;