PHP - How to parse json data and compare it - php

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?

Related

Function for reverse order of values in an array php

I'm new to PHP and I was asked to write a function that accepts an array as a parameter and then prints the array in reverse order. Here is what I have so far:
<?php
function RevOrder ($arr1) {
$arr1 == array();
echo array_reverse($arr1);
}
RevOrder (array(1,4,2,5,19,11,28));
?>
It is supposed to output 28, 11, 19, 5, 2, 4, 1 but I keep getting an array to string conversion error.
echo expects a string while you are passing an array, hence the array to string conversion error. It also looks like you are not properly checking if the param passed is an array. Try this:
<?php
function RevOrder($arr1) {
if (is_array($arr1)) {
return array_reverse($arr1);
}
return false;
}
$reversedArray = RevOrder(array(1,4,2,5,19,11,28));
// Option 1
print_r($reversedArray);
// Option 2
echo(implode(', ', $reversedArray));
<?php
function RevOrder (array $arr1) {
echo implode(", ", array_reverse($arr1));
}
RevOrder (array(1,4,2,5,19,11,28));
But note that this isn't particularly good design - your functions should do one thing. In this case you should instead write a function to print an array according to your liking and then pass it reversed array. Although in this case I guess it's ok to have a helper function for printing the array in reversed order but when you're doing something more complicated you should consider this.
EDIT:
You could do something like this:
function printArray(array $arr){
echo implode(", ", $arr);
}
printArray(array_reverse($arr));
As for why you can't just echo array see this
Arrays are always converted to the string "Array"; because of this,
echo and print can not by themselves show the contents of an array. To
view a single element, use a construction such as echo $arr['foo'].
See below for tips on viewing the entire contents.
Also I added type-hints for array so that when you pass something that's not an array you get an error.

Double array elements in php

I have found some code which is really confusing for me. Maybe it's my mistake or I misunderstand. I have seen some code like this:
function my_compare($a, $b) {
if ($a['practice_id']['practice_url'] == $b['practice_id']['practice-url'])
return $a['practice_location_id']['practice-url'] - $b['practice_location_id']['practise_url'];
else
return $a['practice_id']['practice_url'] - $b['practice_id']['practise_url'];
}
I just need to know the use of practice_url and practise_location_id and practice_url .
Are these both embedded in html name or value? Please help me to understand these.
$a is an associative array. "practice_id" and "practice_url" are keys. As usual, the PHP manual has good info: http://us1.php.net/manual/en/language.types.array.php.
it's a "simple" multi-dimensional php array
In php, arrays can contains number, string, object, or an other array.
for example
$a = array('practice_id' => array('practice_url' => 2));
$b = array('practice_id' => array('practice_url' => 1));
echo $a['practice_id']['practice_url']; // display "2"
This code takes two arrays of arrays. As an example:
$a = array(
'practice_id' => array(
'practice_url'=>'some url'
),
'practice_location_id' => array(
'practice-url'='some other url'
)
);
Of course without seeing the code the arrays could be anything.
$a is an array above. $a['practice_id'] refers to the array inside $a with key 'practice_id' (as an aside this is a strangely named key as it would suggest to me that the entry is a string or number rather than an array). Likewise $a['practice_id']['practice_url'] refers to the some url value.
The function is therefore just checking if certain parts of the array are equal and returning based on that. I.e.
return $a['practice_id']['practice_url'] - $b['practice_id']['practise_url'];
Note that the above is the second strange part. Either practice_url is a number and has an oddly named key or it is indeed a url and the return will attempt to convert both to an integer before returning their difference.

Get JSON data type from associative array in PHP

Evening everyone!
So, I have with me a JSON string...
{"username":"87db3983285d395ca0af9f","password":"f4f0bb1533ef5034ce6b0a8a7c49a43b","email":"xxx#gmail.com","hnum":3,"splicenum":22,"reg_ip":"71.126.122.217","reg_date":1364175245,"cur_ip":"71.126.122.217","ip_array":["71.126.122.217"],"logins":[],"about":""}
And I decode this string into an associative array in PHP using json_decode().
What I'm doing is trying to make 1 single function for querying a JSON object that has been converted to an associative array in PHP. For this function, I am now working on editing/updating fields.
Example:
json_edit(array(
"set"=>array(
"email"=>"yyy#yahoo.com"
)
));
The key "set" means setting the value of a string or boolean.
Another key would be "push" to append to an array, or "delete" to delete a string or an array.
What I'm wondering is, how can I get the data type of the current array part in PHP?
Meaning, how can I get PHP to say, "OK, the field 'username' is a string, and 'ip_array' is an array"?
I don't want to be able to "set" a string value to what is SUPPOSED to be just a boolean, or, an array.
Is there any way to get the JSON data types in PHP?
Thanks so much in advance.
What about gettype(). Gettype() will return the data type of any variable. http://php.net/manual/en/function.gettype.php
I would use something like this;
<?php
function json_edit($json, $changes = array()){
$decoded = json_decode($json);
foreach($changes as $action => $data){
swith($action){
case 'SET':
foreach($data as $key => $value){
$decoded[$key] = $value;
}
break;
case 'DELETE' :
break;
default;
}
}
return json_encode($decoded);
}
?>

PHP: Recursive htmlspecialchars on object

I want to establish a generic sanitizer for my data that comes from various sources. With sanitizing I mean (at this stage) applying htmlspecialchars to strings. Now, the data that comes from these sources can be anything from an object to an array to a string, all nested (and complicated), and the format is always a bit different.
So I thought of a recursive htmlspecialchars function that applies itself to arrays and objects, and only applies htmlspecialchars to strings, but how do I walk an object recursively?
Thanks.
EDIT: I think I should have mentioned this - I am actually building a RIA that relies heavily on JS and JSON for client-server communication. The only thing the server does is fetching stuff from the database and returning it to the client via JSON, in the following format:
{"stat":"ok","data":{...}}
Now as I said, data could be anything, not only coming from a DB in the form of strings, but also coming from an XML
The workflow to process the JSON is as follows:
Fetch data from the DB/XML (source encoding is iso-8859-1)
Put them into the "data" array
Recursively convert from iso-8859-1 to utf-8 using
private function utf8_encode_deep(&$input) {
if (is_string($input)) {
$input = $this -> str_encode_utf8($input);
} else if (is_array($input)) {
foreach ($input as &$value) {
$this -> utf8_encode_deep($value);
}
unset($value);
} else if (is_object($input)) {
$vars = array_keys(get_object_vars($input));
foreach ($vars as $var) {
$this -> utf8_encode_deep($input -> $var);
}
}
}
Use PHP's json_encode to convert the data into JSON
Send (echo) the data to the client
Render the data using JS (e.g. putting into a table)
And somewhere in between that, the data should be somehow sanitized (at this stage only htmlspecialchars). Now the question should have been: Where to sanitize, using what method?
You can try the following
class MyClass {
public $var1 = '<b>value 1</b>';
public $var2 = '<b>value 2</b>';
public $var3 = array('<b>value 3</b>');
}
$list = array();
$list[0]['nice'] = range("A", "C");
$list[0]['bad'] = array("<div>A</div>","<div>B</div>","<div>C</div>",new MyClass());
$list["<b>gloo</b>"] = array(new MyClass(),"<b>WOW</b>");
var_dump(__htmlspecialchars($list));
Function Used
function __htmlspecialchars($data) {
if (is_array($data)) {
foreach ( $data as $key => $value ) {
$data[htmlspecialchars($key)] = __htmlspecialchars($value);
}
} else if (is_object($data)) {
$values = get_class_vars(get_class($data));
foreach ( $values as $key => $value ) {
$data->{htmlspecialchars($key)} = __htmlspecialchars($value);
}
} else {
$data = htmlspecialchars($data);
}
return $data;
}
Output Something like
array
0 =>
array
'nice' =>
array
0 => string 'A' (length=1)
1 => string 'B' (length=1)
2 => string 'C' (length=1)
'bad' =>
array
0 => string '<div>A</div>' (length=24)
1 => string '<div>B</div>' (length=24)
2 => string '<div>C</div>' (length=24)
3 =>
object(MyClass)[1]
...
array
0 =>
object(MyClass)[2]
public 'var1' => string '<b>value 1</b>' (length=26)
public 'var2' => string '<b>value 2</b>' (length=26)
public 'var3' =>
array
...
You would only want to escape when outputting into HTML. And you cannot output a complete array or object into HTML, so escaping everything seems invalid.
You have one level of indirection because of your JSON output. So you cannot decide in PHP what context the data is used for - JSON is still plain text, not HTML.
So to decide whether any data inside the JSON must be escaped for HTML we must know how your Javascript is using the JSON data.
Example: If your JSON is seen as plain text, and contains something like <b>BOLD</b>, then the expected outcome when used inside any HTML is exactly this text, including the chars that look like HTML tags, but no bold typesetting. This will only happen if your Javascript client handles this test as plain text, e.g. it DOES NOT use innerHTML() to place it on the page, because that would activate the HTML tags, but only innerText() or textContent() or any other convenience method in e.g. jQuery (.text()).
If on the other hand you expect the JSON to include readymade HTML that is fed into innerHTML(), then you have to escape this string before it is put into JSON. BUT you must escape the whole string only if you do not want to add any formatting to it. Otherwise you are in a situation that uses templates for mixing predefined formatting with user content: The user content has to be escaped when put into HTML context, but the result must not - otherwise Javascript cannot put it into innerHTML() and enable the formatting.
Basically a global escaping for everything inside your array or object most likely is wrong, unless you know for everything that it will be used in a HTML context by your Javascript.
function htmlrecursive($data){
if (is_array($data) && count($data) > 1){
foreach ($data as &$d){
$d = htmlrecursive($d);
}
} else if (!is_array($data)){
return htmlspecialchars($data);
}
else {
return htmlspecialchars($data[0])
}
}
htmlrecursive($array);
For objects you need to implement The ArrayAccess interface then you can do a array walk recursive
Also check this question Getting an object to work with array_walk_recursive in PHP

Unable to un-serialize an array of arrays with PHP

The array in the database is stored as a serialized string, such as this:
a:1:{i:0;a:4:{s:8:"category";s:26:"Category Name";s:4:"date";s:0:"";s:8:"citation";s:617:"617 Char Length String (shortened on purpose)";s:4:"link";s:0:"";}}
It's structure should resemble the following when unseralized:
array {
id => array { category => Value, date => Value, citation => Value, link => Value }
}
The php code I'm using is:
$prevPubs = unserialize($result[0]['citations']);
The $result[0]['citations'] is the serialized string. $prevPubs will return false. Which indicates an error if I'm not mistaken.
Any help would be greatly appreciated.
b:0 is boolean:false in serialized format. Unserialize would NOT return that exact string, it'd just return an actual boolean FALSE. This means that whatever you're passing into the unserialize call is not a valid serialized string. Most likely it's been corrupted somehow, causing the unserialize call to fail.
in order to handle serialized multidmensional arrays and mysql use this:
<?php
//to safely serialize
$safe_string_to_store = base64_encode(serialize($multidimensional_array));
//to unserialize...
$array_restored_from_db = unserialize(base64_decode($encoded_serialized_string));
?>
i'm pretty sure serialized string in your database is corrupted
You have to unserialize the whole string
$result = unserialize($serialized);
and then use the $result[0]['citation'] index of the result array.

Categories