I have a function that takes the input of a user defined string and an array of data (key=>value), which looks like this;
$text = "Hi! My name is #name, and I live in #location.";
$dataArray = array("name" => "Mikal", "location" => "Oslo, Norway");
function MakeString($text, array $dataArray)
{
// return manipulated string...
}
I would like my function to swap the string #variables with data from the array, where string-variable matches array-key (if it does), so that the function returns:
"Hi! My name is Mikal, and I live in Oslo, Norway."
foreach($dataArray as $key=>$value)
{
$text= str_replace("#".$key,$value,$text);
}
Related
I hope you all having a great day. I'm developing a simple wordpress plugin and I've never worked with JSON encoded data on PHP before so I need some help here.
I have this simple function with a single parameter that's called in a 'foreach' loop and inside this function I have an array of values pulled from DB and it's JSON encoded, it goes like this:
array (size=4)
0 => string '[{"videoUrl":"https://vimeo.com/493156200","playlistID":"7992"}]' (length=64)
1 => string '[{"videoUrl":"https://vimeo.com/365531165","playlistID":"7992"}]' (length=64)
2 => string '[{"videoUrl":"https://vimeo.com/365531139","playlistID":"7992"}]' (length=64)
3 => string '[{"videoUrl":"https://vimeo.com/521605944","playlistID":"7992"}]' (length=64)
My function goes like this:
$playlist_id = 7992;
function videostatuschecker($x){
$unlockedvideos = ['json encoded data illustrated above'];
// x value is like this: $x = 'https://vimeo.com/493156200';
if (in_array($x, $unlockedvideos)){
return 'unlocked';
}
else{
return 'locked';
}
}
Video URL will be passed through my function's parameter variable and playlist ID is defined in the parent function so it's static.
Now what I need is, I need to compare that $x value to "videoUrl" values in the array and compare its 'playlistID' to $playlist_id variable and if they both match, I need the function to return 'unlocked' and vice versa for the else statement. Any help is much appreciated, thank you so much.
You could do something like this:
function videostatuschecker($video_url, $playlist_id){
$unlockedvideos = [
'[{"videoUrl":"https://vimeo.com/493156200","playlistID":"7992"}]',
'[{"videoUrl":"https://vimeo.com/365531165","playlistID":"7992"}]',
'[{"videoUrl":"https://vimeo.com/365531139","playlistID":"7992"}]',
'[{"videoUrl":"https://vimeo.com/521605944","playlistID":"7992"}]'
];
foreach ($unlockedvideos as $unlockedvideo) {
$decoded = json_decode($unlockedvideo);
if ($playlist_id == $decoded[0]->playlistID && $video_url == $decoded[0]->videoUrl) {
return 'unlocked';
}
}
return 'locked';
}
print(videostatuschecker('https://vimeo.com/493156200', 7992));
Please note that your $unlockedvideos is an array of arrays. Is that what you want?
I can't access specific indexes of my array, I want access to the third index of the array that actually holds the zip code of the user to use it in a SELECT statement. Here's the array:
$zip_code = connecting::query('SELECT zipcode FROM accounts WHERE username=:user_name', array(':user_name' => $user_name));
$zipcode = json_encode($zip_code, true);
Here's the output when I print $zipcode:
[{"zipcode":"28262","0":"28262"}]
But when I print $zipcode[2] nothing prints and I can't use it. I can't just access it directly like that? I have used json_encode, var_export, implode, etc. to try to just convert it to a string but it doesn't work.
Here's the query method that I call:
public static function query($query,$params = array())
{
$statement = self :: db()->prepare($query);
$statement->execute($params);
if(explode(' ',$query)[0] == 'SELECT')
{
$data = $statement->fetchAll();
return $data;
}
}
fetchAll returns array of arrays. So, if you print_r(zip_code); you will see something like:
Array (
[0] => Array (
[zipcode] => 28262
[0] => 28262
)
)
So, as you can see - there's no key with index 2 here, only 0 in the outer array and two keys 0 and zipcode in the subarray.
Also, as you can see your data (28262) is duplicated in the subarray under different keys. To avoid this you can provide argument to fetchAll:
$data = $statement->fetchAll(PDO::FETCH_ASSOC);
Totally lost on how to solve. I have a mysql text record which contains the following text:
Hello $someone
When I output it in php, it shows as Hello $someone - which is fine and what I expect.
However, how can I output it in php so that it turns $someone into a php variable, which is assigned in php?... So I'd like my php code like:
$someone = "John Doe";
echo $subject;
returns: Hello John Doe
I've tried looking at variable variables, using $$someone, ${$someone} but always just returns text.
I understand that $someone would always be a text, so would have to have it stored in mysql as something like {$someone} to differentiate it from a dollar amount like $50 etc.
Any help would be greatly appreciated!
Here's an exampe of a simple function that will replace placeholder values in a string. Both the strings ($text) and the data could easily come from the database.
$text = "";
$text .= "<p>Dear {name},</p>\n";
$text .= "<p>Thank you for your order on {order_date}.</p>\n";
$text .= "<p>You order was shipped on {ship_date}.</p>\n";
$data = array(
"name" => "John Doe",
"order_date" => "05/01/2018",
"ship_date" => "05/04/2018",
"order_total" => "$22.50"
);
$textToDisplay = curly_replacer($text,$data);
echo $textToDisplay;
// Function to replace placeholders with data values.
// $str contains placeholder names enclosed in { }
// $data is an associative array whose keys are placeholder,
// and values are the values to replace the placeholders
function curly_replacer($str,$data) {
$rslt = $str;
foreach($data as $key => $val) {
$rslt = str_replace("{".$key."}", $val, $rslt);
}
return $rslt;
}
I am trying to create JSON from a comma delimited string.Now my code is like this
$sql="select Pri_name from nri_privilege";
$getvalue=mysqli_query($mysqli,$sql);
while($result=mysqli_fetch_assoc($getvalue))
{
$getallresults[]=$result;
}
foreach($getallresults as $rereult)
{
print_r($rereult);
name =$rereult['Pri_name'];
name .=$name .',';
//echo $name;
//echo json_encode($name);
}
I am fetching data from database and loop it inside a foreach. How to create JSON from a comma delimited string?
Based on the title of your post this would do what you described.
$array = ["foo", "bar", "bat"]; //some array form e.g. db
$glued = implode(",", $array); //implode it with ,
$json = json_encode($glued); //and json encode it
What I think you really want is this:
$array = ["foo", "bar", "bat"]; //some array form e.g. db
$json = json_encode($array); //json encode the array without step 2.
Guess you want to send the json encoded array over the wire to somewhere else. In this case no need for any implode or explode.
Try This
$sql="select Pri_name from nri_privilege";
$getvalue=mysqli_query($mysqli,$sql);
while($result=mysqli_fetch_assoc($getvalue))
{
$getallresults[]=$result['Pri_name'];
}
echo json_encode($getallresults);
You better not append , manually. Try this,
$names = array();
foreach($getallresults as $rereult){
$names[] = $rereult['Pri_name'];
}
then,
$comma_seperated_list = implode(", ", names);
If you want the above string to be json encoded,
json_encode($comma_seperated_list);
Otherwise you could encode the whole name array like,
json_encode($names);
Hope this helps you!
Hello I have decoded a json string that I sent to my server and Im trying to get the values from him.
My problem is that I cant get the values from the inner arrays.
This is my code:
<?php
$post = file_get_contents('php://input');
$arrayBig = json_decode($post, true);
foreach ($arrayBig as $array)
{
$exercise = $array['exercise'];
$response["exercise"] = $exercise;
$response["array"] = $array;
echo json_encode($response);
}
?>
When I get the answer from my $response I get this values:
{"exercise":null,"array":[{"exercise":"foo","reps":"foo"}]}
Why is $array['exercise'] null if I can see that is not null in the array
Thanks.
From looking at the result of $response['array'], it looks like $array is actually this
[['exercise' => 'foo', 'reps' => 'foo']]
that is, an associative array nested within a numeric one. You should probably do some value checking before blindly assigning values but in the interest of brevity...
$exercise = $array[0]['exercise'];
Because of the [{...}] you are getting an array in an array when you decode your array key.
So:
$exercise = $array['exercise'];
Should be:
$exercise = $array[0]['exercise'];
See the example here.