I have created an array, one of the is intended to be a string used by php to display a field from a record retrieved from sqlite3.
My problem is that ... it doesn't.
The array is defined, "1" being the first database field, and "2" is the second database field:
EDIT : I have re-defined the problem as a script so you can see the whole thing:
//If I have an array (simulating a record retrieved from database):
$record = array(
name => 'Joe',
comments => 'Good Bloke',
);
//then I define an array to reference it:
$fields = array(
1 => array(
'db_index' => 'name',
'db_type' => 'TEXT',
'display' => '$record["name"]',
'form_label' => 'Name',
),
2 => array(
'db_index' => 'comments',
'db_type' => 'TEXT',
'display' => '$record["comments"]',
'form_label' => 'Comments',
),
);
//If I use the lines:
print "expected output:\n";
print " Name = " . $record["name"] ."\n";
print " Comments = " . $record["comments"] ."\n";
//I display the results from the $record array correctly.
//However if I try & use the fields array with something like:
Print "Output using Array values\n";
foreach($GLOBALS["fields"] as $field)
{
$label = $field['form_label'];
$it = $field['display'];
$line = "\"$label = \" . $it .\"\n\"";
print $line;
}
Output:
Expected output:
Name = Joe
Comments = Good Bloke
Output using Array values:
Name = $record["name"]
Comments = $record["comments"]
Don't call variable from string. Just concatenate it :
foreach($GLOBALS["fields"] as $field){
$label = $field['form_label'];
$it = $field['display'];
eval("$it = ".$it);
$line = $label." = ".$it."\n";
print $line;
}
Well, how do it looks ?
Related
First off, sorry if the title is off...it's the best thing I could think of as to what issue I'm facing.
In my database, I have a list of apps. In PHP, I'm pulling their data from their key, and encoding that data into JSON to be printed out (I'm making an API).
However, only the last app gets printed out in JSON. What I need is a JSON array with ANY apps that have the same key so I can loop through them later, and print out their data.
My code:
$getApp = "SELECT * FROM tundra.apps WHERE app_key = '" . $api_key . "'";
$appData = $dbConnection->query($getApp);
if ($appData->num_rows > 0){ // Check if app_key exists
while($row = $appData->fetch_assoc()) { // While retrieving rows
$jsonApp = json_encode(array( // Encode the row data
"app_name" => $row['app_name'],
"app_theme" => array(
"primary_color" => $row['app_primary_color'],
"primary_color_dark" => $row['app_primary_dark_color'],
"accent_color" => $row['app_accent_color'],
),
"app_navigation" => $row['app_navigation'],
"author_info" => array(
"author_name" => $row['app_author_name'],
"author_bio" => $row['app_author_bio'],
"links" => array(
"website" => $row['app_author_website'],
"googleplus" => $row['app_author_gplus'],
"twitter" => $row['app_author_twitter'],
"dribble" => $row['app_author_dribble'],
"behance" => $row['app_author_behance'],
)
),
"app_status" => $row['app_status']
), JSON_UNESCAPED_SLASHES);
}
// Format and print JSON data
echo "<pre>" . prettyPrint($jsonApp) . "</pre>";
} else { // No key found, encode error
$jsonError = json_encode(
array(
array(
"error" => array(
"code" => "8",
"message" => "Invalid API key specified"
)
)
), JSON_UNESCAPED_SLASHES);
echo "<pre>" . prettyPrint($jsonError) . "</pre>";
}
For the above, I tried echoing the JSON data in the while loop, but that (as expected) printed <pre>s for every row.
Here's the JSON output from the above code:
{
"app_name":"Andrew's Second App",
"app_theme":{
"primary_color":"#FFFFFF",
"primary_color_dark":"#E0E0E0",
"accent_color":"#E91E63"
},
"app_navigation":"0",
"author_info":{
"author_name":"Andrew Quebe",
"author_bio":"I'm a developer of stuff.",
"links":{
"website":"http://www.andrewquebe.com",
"googleplus":"https://plus.google.com/+AndrewQuebe",
"twitter":"https://twitter.com/andrew_quebe",
"dribble":"None",
"behance":"None"
}
},
"app_status":"1"
}
Note: the data is perfectly formatted, but I need the data to be in an array and I'm unsure as to how to do this.
The problem is, you're applying json_encode() function in each iteration of while() loop, plus you're overwriting $jsonApp in each iteration. And that's why you're getting that output.
The solution is, create an empty result array outside of while() loop. In each iteration of while() loop, push that array into the result array. And finally after coming out of the loop, apply json_encode() function on the result array and display it.
So your code should be like this:
// your code
if ($appData->num_rows > 0){ // Check if app_key exists
$resultArr = array();
while($row = $appData->fetch_assoc()) { // While retrieving rows
$resultArr[] = array( // Encode the row data
"app_name" => $row['app_name'],
"app_theme" => array(
"primary_color" => $row['app_primary_color'],
"primary_color_dark" => $row['app_primary_dark_color'],
"accent_color" => $row['app_accent_color'],
),
"app_navigation" => $row['app_navigation'],
"author_info" => array(
"author_name" => $row['app_author_name'],
"author_bio" => $row['app_author_bio'],
"links" => array(
"website" => $row['app_author_website'],
"googleplus" => $row['app_author_gplus'],
"twitter" => $row['app_author_twitter'],
"dribble" => $row['app_author_dribble'],
"behance" => $row['app_author_behance'],
)
),
"app_status" => $row['app_status']
);
}
$jsonApp = json_encode($resultArr, JSON_UNESCAPED_SLASHES);
// Format and print JSON data
echo "<pre>" . prettyPrint($jsonApp) . "</pre>";
} else { // No key found, encode error
$jsonError = json_encode(
array(
array(
"error" => array(
"code" => "8",
"message" => "Invalid API key specified"
)
)
), JSON_UNESCAPED_SLASHES);
echo "<pre>" . prettyPrint($jsonError) . "</pre>";
}
In your while loop, you're constantly re-asigning values to $jsonApp. I would recommend adding the values more like this:
$getApp = "SELECT * FROM tundra.apps WHERE app_key = '" . $api_key . "'";
$appData = $dbConnection->query($getApp);
if ($appData->num_rows > 0){ // Check if app_key exists
for($i=0;$row = $appData->fetch_assoc();i++) { // While retrieving rows
$jsonApp[i] = array( // Encode the row data
"app_name" => $row['app_name'],
"app_theme" => array(
"primary_color" => $row['app_primary_color'],
"primary_color_dark" => $row['app_primary_dark_color'],
"accent_color" => $row['app_accent_color'],
),
"app_navigation" => $row['app_navigation'],
"author_info" => array(
"author_name" => $row['app_author_name'],
"author_bio" => $row['app_author_bio'],
"links" => array(
"website" => $row['app_author_website'],
"googleplus" => $row['app_author_gplus'],
"twitter" => $row['app_author_twitter'],
"dribble" => $row['app_author_dribble'],
"behance" => $row['app_author_behance'],
)
),
"app_status" => $row['app_status']
);
}
$json = json_encode($jsonApp,JSON_UNESCAPED_SLASHES);
// Format and print JSON data
echo "<pre>" . prettyPrint($json) . "</pre>";
} else { // No key found, encode error
$jsonError = json_encode(
array(
array(
"error" => array(
"code" => "8",
"message" => "Invalid API key specified"
)
)
), JSON_UNESCAPED_SLASHES);
echo "<pre>" . prettyPrint($jsonError) . "</pre>";
}
This should show a JSON array, with each element in the array representing an individual app entry.
This is the format of JSON. You can not output different shapes. However, when decoding this JSON output, you can either decode objcet or array.
$object = json_decode($json);
$array = json_decode($json, true);
I believe it's because on line 6 of your example you're assigning the output of json_encode to the $jsonApp variable. It would be easier to use an array like so.
$jsonApp[] = array(
And then use json_encode at the end.
echo "<pre>" . prettyPrint(json_encode($jsonApp)) . "</pre>";
I have a PHP array like this:
$arr = array(
'id' => 'app.settings.value.id',
'title' => 'app.settings.value.title',
'user' => 'app.settings.value.user'
);
I want to remove '.id', '.title' and '.user' in the array values. I want to insert the key of this array at the end of the value. I know, that I can get an array key by passing an array and a value to 'array_search', but I want the key within this one array definition - at the end of it's value. Is this possible?
I don't like this, but I guess it's simple and works:
$arr = array(
'id' => 'app.settings.value',
'title' => 'app.settings.value',
'user' => 'app.settings.value'
);
$result = array();
foreach ($arr AS $key => $value) {
$result[$key] = $value . '.' . $key;
}
You're storing app.settings.value which is the same for all array items, so personally I'd prefer:
$arr = array(
'id',
'title',
'user'
);
function prepend_key($key)
{
return 'app.settings.value.' . $key;
}
$result = array_map('prepend_key', $arr);
With $result containing:
array(
'app.settings.value.id',
'app.settings.value.title',
'app.settings.value.user'
);
At the end of the day, either works :)
I have a list of users in my mongodb database, which can then follow each other -pretty standard. Using php I want to check if a specific user is following another user. My data looks like this.
array (
'_id' => ObjectId("56759157e1095db549d63af1"),
'username' => 'Joe',
'following' =>
array (
0 =>
array (
'username' => 'John',
),
1 =>
array (
'username' => 'Tom',
),
),
)
array (
'_id' => ObjectId("56759132e1095de042d63af4"),
'username' => 'Tom',
'following' =>
array (
0 =>
array (
'username' => 'Joe',
),
1 =>
array (
'username' => 'John',
),
2 =>
array (
'username' => 'Sam',
),
),
)
I want a query that will check if Joe is following Sam (which he's not) - so it would produce no results. However, if I was to query the database to check if Tom was following Sam, then it would produce a result to indicate he is (because he is). Do you know how I would do this in PHP? I've experimented with Foreach loops, but I haven't been able to get the results I want.
Make it by DB query, by php it will take more resources
Still if you want by php you can make it so
$following=false;
foreach($data as $v) if ($v['username'] == 'Joe') {
foreach($v['following'] as $v1) if (in_array('Sam', $v1)) {
$following=true;
break 2;
}
}
echo $following;
Such queries are best done in SQL, but if you insist on a PHP-based solution I would suggest to turn the data structure into items keyed by name. Once you have that it is a piece of cake to find relationships:
function organisePersons($data) {
$persons = array();
foreach($data as $person) {
$list = array();
foreach($person["following"] as $following) {
$list[$following["username"]] = $following["username"];
}
$person["following"] = $list;
$person["followedBy"] = array();
$persons[$person["username"]] = $person;
}
// link back to get all "followedBy":
// You can skip this block if you don't need "followedBy":
foreach ($persons as $person) {
foreach($person["following"] as $following) {
echo $person["username"] . " f. $following<br>";
if (!isset($persons[$following])) {
$persons[$following] = array(
"_id" => null, // unknown
"username" => $following,
"following" => array(),
"followedBy" => array()
);
}
$persons[$following]["followedBy"][] = $person["username"];
}
}
// return the new structure
return $persons;
}
So first call the function above with the data you have:
$persons = organisePersons($data);
And then you can write this:
if (isset($persons["Joe"]["following"]["Sam"])) {
echo "Joe is following Sam"; // not in output
};
if (isset($persons["Tom"]["following"]["Sam"])) {
echo "Tom is following Sam"; // in output
};
But also:
echo "Tom is following " . implode($persons["Tom"]["following"], ", ");
// Output: Tom is following Joe, John, Sam
And even the reverse question "Tom is followed by who?":
echo "Tom is followed by " . implode($persons["Tom"]["followedBy"], ", ");
// Output: Tom is followed by Joe
Here is the working script with hard coded values:
$subject->currentCert['tbsCertificate']['extensions'][] = array(
'extnId' => 'id-ce-subjectAltName',
'critical' => false,
'extnValue' => array(
array('dNSName' => 'www.domain1.com'),
array('dNSName' => 'www.domain2.com')
)
);
I would like to update the above script (extnValue section only) to automatically take values from a another array called $OPTIONS["altnames"]
First I convert the following string to an array
$sans = 'www.domain1.com, www.domain2.com';
I converted the string to an array $OPTIONS["altnames"] with the following code:
$OPTIONS["altnames"] = array();
if ( !empty($sans) ) {
if (strpos($sans,",") !== false) {
$sans = str_replace(" ", "", $sans); //remove spaces
$sans = explode(",", $sans); //strip each value after comma to array
foreach ($sans as $value) {
array_push($OPTIONS["altnames"], $value);
}
}
}
Not sure what to do next
You need to add another level of array in the extnValue array when you copy it from $OPTIONS['altnames']:
$extnValues = array();
foreach ($OPTIONS['altnames'] AS $name) {
$extnValues[] = array('dNSName' => $name);
}
$subject->currentCert['tbsCertificate']['extensions'][] = array(
'extnId' => 'id-ce-subjectAltName',
'critical' => false,
'extnValue' => $extnValues
);
This is a newbie question... I have a form in Joomla 3.3 and chronoforms v5 latest... When the form loads the database populates my first select input with "interview dates" from my DB.... works great, once you select the date, the second select input populates with available time slots.... the problem here is the way the DB is output in the array is
Data->
time->7:00am,7:15am,9:30am
Right now when the 2nd select loads it's showing up like this 7:00am,7:15am,9:30am....
I want to be able to make them individual values not all one value...
This is the code I am currently using for the "time" options for the second select input...
<?php
$options = array();
if ( !$form->data['Data'] || count($form->data['Data']) < 1 ) {
// no result was found
$options[] = 'Please select a category';
} else {
foreach ( $form->data['Data'] as $d ) {
$options[$d['interviewdate']] = ($d['time']);
}
}
echo json_encode ($options);
?>
is this possible?
The structure that is needed to create an options list is like this:
[0] => array ('text' => 'aaa', 'value' => 'xxx'),
[1] => array ( . . .
And your data appears to be be in a nested array like $form->data['Data']['time'] ?
In this case the text and value can probably be the same so the code would be something like this:
<?php
$options = array();
if ( !$form->data['Data']['time'] ) {
// no result was found
$options[] = array('text' => 'Please select a category', 'value' => '');
} else {
$data = explode(',', $form->data['Data']['time']);
foreach ( $data as $d ) {
$options[] = array('text' => $d['time'], 'value' => $d['time']);
}
}
echo json_encode($options);
?>
If i am not mistaken your $d['time'] holds values like '7:00am,7:15am,9:30am'. And if this is the case then you can just use explode(',', $d['time']) which will give you array of times instead of string.
$options = array();
$form = new stdClass();
$form->data['Data'] = array(
array(
'interviewdate' => 'date', 'time' => '7:02am,7:25am,9:40am'
),
array(
'interviewdate' => 'date2', 'time' => '7:05am,7:35am,19:40am'
)
);
if ( !$form->data['Data'] || count($form->data['Data']) < 1 ) {
// no result was found
$options[] = 'Please select a category';
} else {
foreach ( $form->data['Data'] as $d ) {
foreach(explode(',', $d['time']) as $time){
$options[] = array($d['interviewdate'] => $time);
}
}
}
echo json_encode ($options);