I created an array using PHP and Microsoft office access database using this code
Code:
<?php try{
$sql = "SELECT * FROM mcc ";
$result = $conn->query($sql);
$row = $result->fetchAll(PDO::FETCH_ASSOC);
print_r($row);
}catch(PDOExepction $e){
echo $e;
}?>
Output:
Array ( [0] => Array ( [sName] => Dihn [Name] => John Parker [BNE] => BOB DIHN ) )
Now I want to use this array for further operation like make an excel file and all but i cant because array contains []"Square brackets" ,"String without double quotation " ,"string with space" and no ","(comma) between two rows.
how can i simplify this code to use like normal array or any other suggestion.please help me
$row is an array (as PHP tells you in the output of print_r), so the array exists. print_r just outputs a more human-readable form of the array, that's exactly what the function was designed for. If you don't want that, then you are using the wrong function.
If you want to process the array using PHP, don't echo it, but use it directly, e.g. like this:
$rows = $result->fetchAll(PDO::FETCH_ASSOC);
// Rows is an array of the results
foreach($rows as $row) {
$thename = $row['Name'];
// Do something with the data
}
If you want to output the array in valid PHP syntax, the easiest solution is to replace print_r with var_export:
$row = $result->fetchAll(PDO::FETCH_ASSOC);
var_export($row);
You did not give the slightest hint about how you want to process the output. However, if you want to process the output of your script, it might be easier to use JSON:
echo json_encode($row);
Related
I'm trying to turn my results into a json encoded string. I know that now working on an external api seems a bit much, but I do think that it's something that will come in handy as times goes on. Currently, I use the following function:
//API Details
public function APIReturnMembers() {
$query = <<<SQL
SELECT uname
FROM {$this->tprefix}accounts
SQL;
$encode = array();
$resource = $this->db->db->prepare( $query );
$resource->execute();
foreach($resource as $row) {
$encode[] = $row;
}
echo json_encode($encode);
}
It does what it's supposed to as far as returning results go, e.g.:
[{"uname" : "guildemporium"}, {"uname" : "doxramos"}]
When I saw that I was ecstatic! I was on my way to implementing my own API that others could use later on as I actually got somewhere! Now of course I have hit a hickup. Testing my API.
To run the code to get the results I used
$api_member_roster = "https://guildemporium.net/api.php?query=members";
$file_contents = #file_get_contents($api_member_roster); // omit warnings
$memberRoster = json_decode($file_contents, true);
print_r($memberRoster);
The good news!
It works. I get a result back, yay!
Now the Bad.
My Result is
[
0 => ['uname' => 'guildemporium'],
1 => ['uname' => 'doxramos']
]
So I've got this nice little number integer interrupting my return so that I can't use my original idea
foreach($memberRoster as $member) {
echo $member->uname;
}
Where did this extra number come from? Has it come in to ruin my life or am I messing up with my first time playing with the idea of returning results to another member? Find out next time on the X-Files. Or if you already know the answer that'd be great too!
The numbered rows in the array as the array indices of the result set. If you use print_r($encode);exit; right before you use echo json_encode($encode); in your script, you should see the exact same output.
When you create a PHP array, by default all indices are numbered indexes starting from zero and incrementing. You can have mixed array indices of numbers and letters, although is it better (mostly for your own sanity) if you stick to using only numbered indices or natural case English indices, where you would use an array like you would an object, eg.
$arr = [
'foo' => 'bar',
'bar' => 'foo'
];
print_r($arr);
/*Array
(
[foo] => bar
[bar] => foo
)*/
$arr = [
'foo','bar'
];
/*Array
(
[0] => foo
[1] => bar
)*/
Notice the difference in output? As for your last question; no. This is normal and expected behaviour. Consumers will iterate over the array, most likely using foreach in PHP, or for (x in y) in other languages.
What you're doing is:
$arr = [
['abc','123']
];
Which gives you:
Array
(
[0] => Array
(
[0] => abc
[1] => 123
)
)
In order to use $member->foo($bar); you need to unserialize the json objects.
In you api itself, you can return the response in json object
In your api.php
function Execute($data){
// Db Connectivity
// query
$result = mysqli_query($db, $query);
if( mysqli_num_rows($result) > 0 ){
$response = ProcessDbData($result);
}else{
$response = array();
}
mysqli_free_result($result);
return $response;
}
function ProcessDbData($obj){
$result = array();
if(!empty($obj)){
while($row = mysqli_fetch_assoc($obj)){
$result[] = $row;
}
return $result;
}
return $result;
}
function Convert2Json($obj){
if(is_array($obj)){
return json_encode($obj);
}
return $obj;
}
Calling api.php
$result = $this->ExecuteCurl('api.php?query=members');
print_r($result);
here you $result will contain the json object
I am new to php programming. Here in my project I am trying to parse JSON data coming from php web service. Here is the code in web service.
$query = "select * from tableA where ID = 1";
$result = mysql_query($query);
if (mysql_num_rows($result) > 0) {
$arr= array();
while ($row = mysql_fetch_assoc($result)) {
$arr['articles'][] = $row;
}
header('Content-type: application/json');
echo json_encode($arr);
}
else{
echo "No Names";
}
This is giving me data in this JSON format.
{"articles":[{"ID":"1","Title":"Welcome","Content":"This is the first article."}]}
Now here is my php page code.
<?php
$jfile = file_get_contents('http://localhost/api/get_content.php');
$final_res = json_decode($jfile, true) ;
var_dump( $final_res );
$content = $final_res->articles->Content;
?>
I want to show the content on webpage.
I know code at var_dump( $final_res ); is working. But after that code is wrong. I tried to look at many tutorials to find the solution but didn't find anyone. I don't know where I am wrong.
The second parameter of json_decode determines whether to return the result as an array instead of an object. Since you set it to true your result is an array and not an object.
$content = $final_res['articles'][0]['Content'];
As an alternative answer, if you want to use it as an object, use this code:
$a = '{"articles":[{"ID":"1","Title":"Welcome","Content":"This is the first article."}]}';
$final_res = json_decode($a);
echo '<pre>';
print_r($final_res);
echo '</pre><br>';
Note that I removed the second part (true) from the json_decode
Output:
stdClass Object
(
[articles] => Array
(
[0] => stdClass Object
(
[ID] => 1
[Title] => Welcome
[Content] => This is the first article.
)
)
)
Accessing Content:
echo 'Content: ' . $final_res->articles[0]->Content;
Output:
Content: This is the first article.
Run code
I have an array that is filled with different sayings and am trying to output a random one of the sayings. My program prints out the random saying, but sometimes it prints out the variable name that is assigned to the saying instead of the actual saying and I am not sure why.
$foo=Array('saying1', 'saying2', 'saying3');
$foo['saying1'] = "Hello.";
$foo['saying2'] = "World.";
$foo['saying3'] = "Goodbye.";
echo $foo[array_rand($foo)];
So for example it will print World as it should, but other times it will print saying2. Not sure what I am doing wrong.
Drop the values at the start. Change the first line to just:
$foo = array();
What you did was put values 'saying1' and such in the array. You don't want those values in there. You can also drop the index values with:
$foo[] = 'Hello.';
$foo[] = 'World.';
That simplifies your work.
You declared your array in the wrong way on the first line.
If you want to use your array as an associative Array:
$foo=Array('saying1' => array (), 'saying2' => array(), 'saying3' => array());
Or you can go for the not associative style given by Kainaw.
Edit: Calling this on the not associative array:
echo("<pre>"); print_r($foo); echo("</pre>");
Has as output:
Array
(
[0] => saying1
[1] => saying2
[2] => saying3
[saying1] => Hello.
[saying2] => World.
[saying3] => Goodbye.
)
Building on what #Answers_Seeker has said, to get your code to work the way you expect it, you'd have to re-declare and initialise your array using one of the methods below:
$foo=array('saying1'=>'Hello.', 'saying2'=>'World.', 'saying3'=>'Goodbye.');
OR this:
$foo=array();
$foo['saying1'] = "Hello.";
$foo['saying2'] = "World.";
$foo['saying3'] = "Goodbye.";
Then, to print the contents randomly:
echo $foo[array_rand($foo)];
I am using this code to build an array and encode it to JSON.
while($row = mysqli_fetch_array($sql)) {
$results[] = array(
'wdatatype' => $row['wdatatype'],
'wdb' => $row['wdb'],
'wbyte' => $row['wbyte'],
'wbit' => $row['wbit'],
'bitval' => $row['bitval'],
);
}
$json = json_encode($results);
echo $json;
The output is this
[{"wdatatype":"DB","wdb":"100","wbyte":"0","wbit":"0","bitval":"1"}]
But for my jQuery script I need the output to be
{"wdatatype":"DB","wdb":"100","wbyte":"0","wbit":"0","bitval":"1"}
How do I accomplish this?
Thanks!
You're problem seems to stem from the fact that you're creating a multi-dimensional array. You're pushing an array as an element of the existing $results array. For you're desired output, $results should be an associative array, not an array of associative arrays.
Provided there is only one row in your result set, try this instead:
// Remove the while loop if you're only returning a single row
// such as with a LIMIT = 1 clause in your SQL statement.
$row = mysqli_fetch_array($sql);
// Push the single row as an array into $result
$results = array(
'wdatatype' => $row['wdatatype'],
'wdb' => $row['wdb'],
'wbyte' => $row['wbyte'],
'wbit' => $row['wbit'],
'bitval' => $row['bitval'],
);
// Now echo the json_encode
echo json_encode($results);
When converted using json_encode, the above will turn into a single object like so:
{"wdatatype":"DB","wdb":"100","wbyte":"0","wbit":"0","bitval":"1"}
rather than an array of objects.
Note: As #PankajGarg and #AmalMurali pointed out this should be used if you're only returning a single row. Failing to remove the while loop and returning a result set of more than one row will yield you a return of the last row only.
For a result set containing multiple rows, your current structure will work perfectly.
Alternatively as #Nilpo pointed out, you can simplify the above process by using mysqli_fetch_assoc() to return an associative array for you.
$row = mysqli_fetch_assoc($sql);
// Now echo the json_encode
echo json_encode($row);
When a retrieve the according data from the database then encode it as json then pass it to the view:
$json_data = json_encode($x);
$search_results['search_results'] = $json_data;
$this->load->view('findquestions',$search_results);
If I display this in the view we get:
[{"question_title":"java"},{"question_title":"big java book"}]
How can the question_titles so "java" be extracted and presented as a url link or inside a table
Since you're passing the json-string directly to the view and then process it (for display) through PHP, you should be able to use PHP's json_decode() to convert it into an object (or array) to use it in a more-friendly manner:
// use json_decode with `true` to get an associative array
$results = json_decode($search_results['search_results'], true);
You can now access the data either directly or within a loop:
// direct access
$title1 = $results[0]['question_title'];
// in a loop
foreach ($results as $result) {
echo 'Title: ' . $result['question_title'];
}
For reference, using the sample-data supplied in the question, a print_r() of the data:
print_r($results);
Array (
[0] => Array (
[question_title] => java
)
[1] => Array (
[question_title] => big java book
)
)
To process the results in PHP
In your controller:
$search_results['search_results'] = $x; //store the array
$this->load->view('findquestions',$search_results); //pass the results as PHP array to view
In your view:
foreach($search_results as $result){
echo $result['question_title'];
}