How to parse WordPress wpDataTable data using PHP? - php

I have the below formatted code from database.
a:9:{i:8053;a:26:{s:4:"name";s:0:"";s:12:"squareseaten";s:0:"";s:4:"wins";s:0:"";s:9:"timetaken";s:0:"";s:10:"tubeseaten";s:0:"";s:12:"gummieseaten";s:0:"";s:12:"pepperseaten";s:0:"";s:10:"chipseaten";s:0:"";s:13:"bottlechugged";s:1:"1";s:17:"boxesofbiteseaten";s:0:"";s:19:"boxesofbrutalseaten";s:0:"";s:14:"crunchieseaten";s:0:"";s:17:"boxesofdncvseaten";s:0:"";s:15:"bottlesconsumed";s:0:"";s:12:"pieceschewed";s:0:"";s:14:"additionalnuts";s:1:"1";s:15:"additionaltimes";s:0:"";s:18:"additionalattempts";s:0:"";s:3:"pts";s:0:"";s:1:"p";s:0:"";s:1:"w";s:0:""; ...
This looks like JSON. But it's not actually.
This was actually generated by a WordPress plugin called wpDataTables.
How can I parse through this data in PHP?

That's a serialized string. Run that string through unserialize() and you'll get an array.

This is a serialized string you need to use unserialize()
Ex:
<?php
$data = 'a:3:{i:0;s:3:"Red";i:1;s:5:"Green";i:2;s:4:"Blue";}';
$test = unserialize($data);
var_dump($test);
?>
Output
array(3) { [0]=> string(3) "Red" [1]=> string(5) "Green" [2]=> string(4) "Blue" }
The unserialize() function converts serialized data into array.
Syntax:
unserialize(string, options);
string(Required): Specifies the serialized string.
options : Specifies options to be provided to the function, as an associative array. Can be either an array of class names which should be accepted, false to accept no classes, or true to accept all classes. True is default.

Related

in php, How can I extract a JSON from an array?

I'm receiving a string from the database and I only want to use the JSON so I can use a json_decode on it.
this is the string:
array(1) { [0]=> array(4) { ["reporte_id"]=> int(1) ["tabla_id"]=> int(1) ["configuracion"]=> string(1000) "{"tabla":"servtp","config":[{"name":"Client","type":"smallint","notnull":"0","pk":"0"},{"name":"Distribuidor_","type":"varchar(40)","notnull":"0","pk":"0"},{"name":"Branch","type":"smallint","notnull":"0","pk":"0"},{"name":"Cve","type":"smallint","notnull":"0","pk":"0"},{"name":"FechaApertura","type":"date","notnull":"0","pk":"0"},{"name":"FechaFactura","type":"date","notnull":"0","pk":"0"},{"name":"Dias","type":"smallint","notnull":"0","pk":"0"},{"name":"WorkingDays","type":"real","notnull":"0","pk":"0"},{"name":"Mes_","type":"smallint","notnull":"0","pk":"0"},{"name":"NumeroOT","type":"varchar(10)","notnull":"0","pk":"0"},{"name":"VentasNetas_","type":"real","notnull":"0","pk":"0"},{"name":"TipoOrden","type":"varchar(30)","notnull":"0","pk":"0"},{"name":"Type","type":"varchar(3)","notnull":"0","pk":"0"},{"name":"Taller","type":"varchar(30)","notnull":"0","pk":"0"},{"name":"Clasificacion_","type":"varchar(16)","notnull":"0","pk":"0"},{"name":"Retencion_","type":"varchar(1)","notnull":" ["nom_reporte"]=> string(33) "Monthly Service Operation Report " } }
If the variable is called $variable, ... you have to:
$json = $archivio[0]['configuration'];
$arrayConf = json_decode($json);
The string you are presenting is a var_dump of a php array, it is not properly formed. Where you are getting that string from should fix their side to properly format the array formatting.

Issue passing array as argument [to InvokeArg()] in php - var_dump are the same but only one works?

Backstory: Creating function to handle mysqli and binding data. All code is in the scope of a single function. Using ReflectionClass to programmatically invoke mysqli_stmt_bind_param function (as number of arguments vary).
Problem: I am having an issue passing an array I built up programmatically ($refArr). When I compare the var_dump of this array (with a sample array I created directly), the two arrays are identical. The invokeArg() method runs with the sample array ($refArr_sample) but not with $refArr.
Here is the output for the code shown below:
array(3) { [0]=> string(2) "si" [1]=> string(5) "user1" [2]=> int(0) } - output of refArr
array(3) { [0]=> string(2) "si" [1]=> string(5) "user1" [2]=> int(0) } - output of refArr_sample
$refArr_sample = array("si", "user1", 0);
// var_dump are equal in type and length
var_dump($refArr);
var_dump($refArr_sample);
$ref = new ReflectionClass('mysqli_stmt');
$method = $ref->getMethod("bind_param");
$method->invokeArgs($res,$refArr); // Doesn't Work ?????????
//$method->invokeArgs($res,$refArr_sample); // Works ?????????
$res->execute();
I am unsure how to fix the problem (as I've no clue what the problem is). I don't think this is an issue with references. Once the var_dump is the same I thought it wouldn't have mattered. I also did a === comparison between the two arrays which came back true. At this point I am lost as to why it isn't working.
I can link the complete code (self contained function) if required.
You should note that the values in the passed array must be references (as of PHP 5.3), whereas your $refArr is built dynamically.
...
//assign references
foreach ($refArr as $key => $value) {
$refArr[$key] =& $refArr[$key];
}
$method->invokeArgs($res,$refArr);
...

Getting Value from Object with Characters in Element Name

I have an object being passed into a function which I have no control over and it is in the below format, with the root being 'entity'.
object(SimpleXMLElement)#6 (1) { ["#attributes"]=> array(2) { ["id"]=> string(2) "12" ["name"]=> string(17) "Test Object Value" } }
Now I'm trying to pull out just the name by using both the below snippets but both output empty values.
entity[0]->name;
and
entity->{'#attributes'}->name;
Is there a special way to deal with characters in element names when the curly brackets format doesn't work?
You need to use attribute() function for getting the attributes in a simpleXML object. Your code should be something like:
$parsed = $simplexmlObject->entity->attribute()->desiredProperty;
Update: Got this technique from a question asked from me, How to parse value `#attribute` from a SimpleXMLObject in PHP
You can get the name attribute as follows:
$name = $entity->attributes()->name;
echo $name;

PHP Convert array element to string prints "Array"

I query a database to obtain an array of results.
$usersArray = $db->getAllUsers(); // db-Query
If I print out the array's var_dump, its content is structured in form of other arrays:
array(9) { [0]=> **array**(1) { ["column"]=> string(20) "..." } [1]=> **array**(1) { ["column"] (remaining 8 are the same).
Now I need these values (which are correct, so far) to be casted as strings, so that:
array(9) { [0]=> **string**(1) { ["column"]=> string(20) "..." } [1]=> **string**(1) { ["column"] ....
There are several answers to this here and elsewhere, such as
-array_map: here I can actually cast the content as string, but- it prints "Array" instead the value. It tried then getting the content via
$users = array_map('strval',implode( $usersArray));
$users = array_map('strval', print_r($usersArray));
Neither of those worked.
Is there a method through which I could cast the content as string and get the content ? Or should I rewrite the query to format the result as strings ?
You have a wrong understanding of types or at least this:
array(9) { [0]=> **string**(1) { ["column"]=> string(20) "..." } [1]=> **string**(1) { ["column"] ....
doesn't make any sense. You believe you want elements to be of type string but yet contain array data which really doesn't work.
What you actually want is a different array structure but you are heading in the wrong direction for that.
You basically have two options:
Modify the getAllUsers() method in a way that returns your data in a structure you actually need.
Modify the data after you have received it. Obviously there's no builtin function convert_data_to_how_i_want_them() - so a basic understanding of arrays is required.
Basically you create a new array and copy those values you need to the position you need them at.
Something like this should do the trick in this case:
$out = array();
foreach($in as => $value) {
$out[] = $value['column'];
}

PHP Function producing two iterations of an array, in the same array

I've got a function that gets data from a NoSQL database, and if it's not available then it goes to a MySQL database to get the data but the issue is, the function is putting the data into the array twice and I can't figure out why.
Expected result
array(2) {
["id"]=> string(2) "30"
["username"]=> string(8) "Username" }
Actual result
array(4) {
[0]=> string(2) "30"
["id"]=> string(2) "30"
[1]=> string(8) "Username"
["username"]=> string(8) "Username" }
Code
Code that is irrelevant to the problem is removed and replaced by pseudo code comments.
$Connection = $this->Connect("MySQLi");
$Data = MySQLi_Fetch_Array(
MySQLi_Query($Connection["MySQLi"], $Options["Query"])
);
echo "Got array (MySQLi).";
It's worth noting that the string "Got array (MySQLi)." only appears once.
MySQLi_Fetch_Array gets duplicated data in one array - with numerical and associative indexes at the same time
Use mysqli_fetch_assoc instead to have only associative
mysqli_fetch_array() takes a parameter, resulttype, which by default is set to MYSQLI_BOTH.
By using the MYSQLI_ASSOC constant this function will behave identically to the mysqli_fetch_assoc(), while MYSQLI_NUM will behave identically to the mysqli_fetch_row() function. The final option MYSQLI_BOTH will create a single array with the attributes of both.
mysqli_fetch_assoc fetches an associative array, while mysqli_fetch_row fetches an array with numeric indexes.
mysqli_fetch_array with the parameter MYSQLI_BOTH will fetch both named (associative) indexes and numeric indexes in the same array.

Categories