How to Extract Data from a field with multiple values? - php

IP.Nexus puts custom fields into a table all muddled up into one row and some how pulls the correct data out.
basically my custom fields row looks like so:
a:2:{i:2;s:4:"Test";i:3;s:10:"Accounting";}
How do i select what item to pull as i would like to out put just one item not the whole row, is it with delimiters or string splitter, as i am novice with this part of mySQL
Cause i would like to echo out just the advertising on its own and also vice versa for the testing.
Thanks in advance

It's a serialized array using serialize() function so you can get its contents using unserialize($YourString);.
But I see that you string is corrupted for deserialization, because s:4: in s:4:"advertising" says that after s:4: 4 character long string is expected that advertising is not.

The data in the database is in serialized(json) form.You can turn it into simple array using unserialize.
For example;if $mystr is your string
write
$mystring=unserialize($mystring)
You will get normal array of this string
You can do
foreach($mystring as $str){
$ads[]=$str['advertising'];
}
and the resulting array $ads will be the ads you like in simple array form

Since this looks as JSon, you can use a PHP JSon module to parse each row from MySQL.
<?php
(...)
while (...) {
$obj = json_decode($row);
// do something with $obj
}

Related

PHP: Converting this data structure into an associative array

I have a field created by word press which contains data with the following structure.
a:16:{s:7:"country"
s:14:"United Kingdom"
s:7:"form_id"
s:2:"35"
s:9:"timestamp"
s:10:"1560869327"
s:7:"request"
s:0:""
s:8:"_wpnonce"
s:10:"125"
s:16:"_wp_http_referer"
s:1:"/"
s:17:"ajaxy-umajax-mode"
s:8:"register"
s:10:"first_name"
s:5:"xxxxx"
s:9:"last_name"
s:5:"xxx"
s:10:"user_email"
s:28:"xxx#xxx.co.uk"
s:7:"Company"
s:16:"xxx LTD"
s:12:"phone_number"
s:10:"0123456789"
s:8:"user_url"
s:20:"http://www.test.com"
s:15:"company_address"
s:18:"999 LockSmith Lane"
s:12:"display_name"
s:12:"XXXX"
s:10:"user_login"
s:10:"xxx123"
}
I want to convert this to an array so I can read the properties of it.
I tried converting it to json but its not json.
Any ideas on how I can parse this data, or access its properties in PHP.
I can not access this data through wordpress as my PHP script is part of something else.
Seems like a serialized array. Try unserializing it to convert it back to normal, see example.
This is Actually not a json.This is an array in serialized format you can just unserilize it by using this function
maybe_unserialize($YOUR_ARRAY).
maybe_unserialize is a wordpress default function to unserialize the array

How to remove json element?

I'am using dataTables plugin for my table, and it has an json data from the database like :
{"sEcho":0,
"iTotalRecords":1,
"iTotalDisplayRecords":1,
"aaData":[["contentFieldA","contentFieldB","contentFieldC"],
["contentFieldA","contentFieldB","contentFieldC"]],
"sColumns":"fieldA,fieldB,fieldC"}
for some reason I need to remove the "aaData" and "sColumns" value on the first index (so "contentFieldA" and "fieldA" should be removed). and the json data will be :
{"sEcho":0,
"iTotalRecords":1,
"iTotalDisplayRecords":1,
"aaData":[["contentFieldB","contentFieldC"],
["contentFieldB","contentFieldC"]],
"sColumns":"fieldB,fieldC"}
Can anyone help me.. Thanks
If you have :
var test = {"sEcho":0,
"iTotalRecords":1,
"iTotalDisplayRecords":1,
"aaData":[["contentFieldA","contentFieldB","contentFieldC"],
["contentFieldA","contentFieldB","contentFieldC"]],
"sColumns":"fieldA,fieldB,fieldC"};
aaData is an array of arrays, so remove first index of each subarray like this :
for (var i=0;i<test['aaData'].length;i++) {
test['aaData'][i].splice(0,1);
}
deleting first index from sColumns is a little bit harder, since it is a string :
test['sColumns']=test['sColumns'].split(',').splice(1,2).join();
Notice that splice(1,2) is hardcoded, if you have 4 columns it should be splice(1,3), 5 columns splice(1,4) and so on.
Running those two cleanups will give the desired result.
Since it is in JSON, you can use regular expression and remove what you want:
PHP: http://au1.php.net/preg_replace
JS: http://www.w3schools.com/jsref/jsref_replace.asp

I'm fairly new to JSON, and I'm trying to get the user data from google + JSOn Code is

I'm fairly new to JSON, and I'm trying to get the user data from google +
JSOn Code is
https://www.googleapis.com/plus/v1/people?query=saurabh+sharma&key=AIzaSyADJjj8IeKuGb-woleHKTVouSlvAJUpTrs
Please help me to retrive the user profile.. in php
var_dump(json_decode(file_get_contents('https://www.googleapis.com/plus/v1/people?query=saurabh+sharma&key=AIzaSyADJjj8IeKuGb-woleHKTVouSlvAJUpTrs')));
It's indeed a bit of a mixed potato-puree (=confusion) between arrays and objects. That JSON is entirely object, except for the array 'items', which is an array of... objects.
Try this:
<?php
$strUrl = "https://www.googleapis.com/plus/v1/people?query=saurabh+sharma&key=AIzaSyADJjj8IeKuGb-woleHKTVouSlvAJUpTrs";
$strContents = file_get_contents($strUrl);
$objPeopleFeed = json_decode($strContents);
//It's an array of objects, so:
echo "<h1>{$objPeopleFeed->title}</h1>";
foreach($objPeopleFeed->items as $objUser)
{
echo "
<p>
<img src='{$objUser->image->url}' />
<a href='{$objUser->url}'>{$objUser->displayName}</a>
<i>{$objUser->objectType}</i>
</p>";
}
?>
What it does: It gets the contents from the web (which is JSON), interpretes it as JSON into valid PHP structures. From the structure, we print the title as a H1 header. From the items, which is an array, we loop through each one, print the image src from $objUser->image->url, print the user link $objUser->url with its name $objUser->displayName, and optionally its type of object $objUser->objectType that is registered on Google.
Because everything is kind of objects, you use the object to variable syntax '->xyz' instead of array indexes '["xyz"]', and I guess you got stuck there. The $objPeopleFeed->items is a non-associative array, so you use numbers to loop through the items ($objPeopleFeed->items[0] for the first item, 1 for the second, etc...). As a final cookie to you, you can use count($objPeopleFeed->items) as a results count.

mySql retrieving data between square brackets

I have strings of data in a field named content, one record may look something like:
loads of text ... [attr1] some text [attr2] more text [attr3] more text etc...
What I'm looking to do is get all the text within the square brackets; so that I can put it into a PHP array. Is this even possible with mySql?
I've seen the following post: Looking to extract data between parentheses in a string via MYSQL, but they are looking to only extract one value from between their parentheses, I have an unknown number of them. After reading that post I've though of doing something like the following;
SELECT substr(content,instr(content,"["), instr(content,"]")) as attrList from myTable
Which would grab me the following:
[attr1] some text [attr2] some more text [attr3]
and I can use PHP to strip the rest of the text out and then explode the string into an array, but is there a better way to do this just using mySql where I can retrieve something like:
[attr1][attr2][attr3]
I was thinking perhaps regex, but I see that just returns a true of false which doesn't help me a lot.
After even more research, I'm not sure it's possible in mySql, and I might need the results in string or array form depending on where I'm using them in my app.
So I've created a new method to return the list after I've got the data from the database (with a little help from this post: PHP: Capturing text between square brackets):
public function attrList($array=false)
{
preg_match_all("/\[.*?\]/",$this->content,$matches);
$params = str_replace(array('[',']'),'',$matches[0]);
return ($array===false) ? implode(', ',$params) : $params;
}

zend php multiple array json_encoding

I have a problem with the json functionality in zend and js.
I try to encode a single array containing some number of models like this:
echo json_encode(Application_Model_Marker::getMarkers());
var mark = JSON.parse(jsonVal); //in js
where getMarkers is a static method that returns an array of marker models.
This works fine and when I parse it in the js script and try accessing the values of the json object it works fine.
If however I try to create and send an array of array like this:
$allData = array();
$allData['info'] = Application_Model_Marker::getMarkers();
$allData['openingHours'] = Application_Model_Openinghours::getOpeningHours();
$allData['happyHours'] = Application_Model_Happyhour::getHappyHours();
echo json_encode($allData);
It still sends all the correct information when I try to alert(jsonVal.responseText); in js.
It has three arrays each containg some arrays of objects.
However when I try to initialize a variable to the parsed json object like in the first example, I can't access the values and it seems some kind of error occurs as the program stops when I try it.
I don't quite get it as it has all the correct info when i just try to print the response text from the encoded json object.
Any ideas how to do this multidimensional json encoding?
Try this, Hopefully it'll work :
<sctript>
var mark;
eval("mark = "+jsonVal+";");
</sctrip>

Categories