Parsing - JSON - Array of Arrays - php

A JSON array has the form:
[[a,b,c],[a,b,c],[a,b,c]]
Is there a better way than split?

No, this is most certainly not the best way to parse JSON. JSON parsers exist for a reason. Use them.
In JavaScript, use JSON.parse:
var input = '[[1,2,3],[1,2,3],[1,2,3]]';
var arrayOfArrays = JSON.parse(input);
In PHP, use json_decode:
$input = '[[1,2,3],[1,2,3],[1,2,3]]';
$arrayOfArrays = json_decode($input);

You do not need to use regular expressions. As has been mentioned, you must first have valid JSON to parse. Then it is a matter of using the tools already available to you.
So, given the valid JSON string [[1,2],[3,4]], we can write the following PHP:
$json = "[[1,2],[3,4]]";
$ar = json_decode($json);
print_r($ar);
Which results in:
Array
(
[0] => Array
(
[0] => 1
[1] => 2
)
[1] => Array
(
[0] => 3
[1] => 4
)
)
If you want to decode it in JavaScript, you have a couple options. First, if your environment is new enough (e.g. this list), then you can use the native JSON.parse function. If not, then you should use a library like json2.js to parse the JSON.
Assuming JSON.parse is available to you:
var inputJSON = "[[1,2],[3,4]]",
parsedJSON = JSON.parse(inputJSON);
alert(parsedJSON[0][0]); // 1

In JavaScript , I think you can use Eval() → eval() method...

Related

How can I parse/extract from a string in PHP? Specifically something between quotes

I have a string like this
{"2":{"name":"Moon Center","value":"moon7","value_raw":"moon7","id":2,"type":"select"},"3":{"name":"Multiple Choice","value":"Second Choice","value_raw":"Second Choice","id":3,"type":"radio"}}
How do I get for example, the content inside value to a variable? And I would want to be able to get it for every item with value in there. There will be several that come from a form in a single string.
This is the response from a form that stores the whole string in a string. Kinda wish it was an array but this is what i'm working with.
Your string is actually a JSON value. To get the data out of it, you must first json_decode it to an array (or object). If you choose an array, you can then use array_column to get all the 'value' values:
$json = '{"2":{"name":"Moon Center","value":"moon7","value_raw":"moon7","id":2,"type":"select"},"3":{"name":"Multiple Choice","value":"Second Choice","value_raw":"Second Choice","id":3,"type":"radio"}}';
$array = json_decode($json, true);
print_r(array_column($array, 'value'));
Output:
Array (
[0] => moon7
[1] => Second Choice
)
Demo on 3v4l.org

How to display this json in jquery

I not which part I am doing wrong. I couldn't able to fetch this array to display. Can someone please help me with this. I am new to JSON.
Array
(
[0] => [{"id":2,"request_id":2,"message":"wqvewq ewq wq ewq e wqwe qwe ","user_id":1,"created_at":"2014-05-30 16:21:28","updated_at":"2014-05-30 16:21:28"},{"id":3,"request_id":2,"message":"as aS A","user_id":2,"created_at":"2014-05-30 17:18:37","updated_at":"2014-05-30 17:18:37"},{"id":4,"request_id":2,"message":"AS As a","user_id":2,"created_at":"2014-05-30 17:18:43","updated_at":"2014-05-30 17:18:43"}]
[1] => [{"id":1,"request_id":2,"message":"sfsdfds sdfds f ","user_id":2,"created_at":"2014-05-30 17:15:16","updated_at":"2014-05-30 17:15:16"}]
[2] => []
)
The output you have quoted looks like PHP print_r output, and it's certainly not legal JSON.
Perhaps you need the PHP json_encode function, to get real JSON out of your PHP code?
It's not one json string but an array of json strings.
You have to first loop thru the array, parse the json and show the variables that you want in your html with jQuery.
You can find a lot of info on the internet and stackoverflow on this subject.
these are the possibilitys you have
var data = array();
for(var i=0;i<yourArray.length;i++)
data[i] = $.parseJSON(yourArray[i]);
or (untested)
var data = JSON.parse(JSON.stringify({yourArray: yourArray}));

whats programming language is this syntax?

while I was searching through some file in a php library, i found some documents like this
a:1:{i:0;a:1:{s:3:"cnt";s:1:"1";}}
This is definitely not JSON. Does any one know what is this? or is it a custom syntax for the guy who wrote the library ?
That is a serialized data and not any programming language syntax.
For your understanding...
<?php
$arr = ['a'=>1,'b'=>2,'cnt'=>5];
echo serialize($arr);
OUTPUT :
a:3:{s:1:"a";i:1;s:1:"b";i:2;s:3:"cnt";i:5;}
Language in Php more info on this link unserialize
This is basically a serailize form of array
of follwoing array
Array
(
[0] => Array
(
[cnt] => 1
)
)
You can get it back by into array
$a = 'a:1:{i:0;a:1:{s:3:"cnt";s:1:"1";}}';
$unserailize_a = (unserialize($a));
To convert an array into string us the Serialize

store more than one value with same para name of URL into array

min=112&max=131&sid=1&sid=46&sid=6
The above is the code snippet of URL. my question is how store all sid value into $idArr in PHP and output will be as below.
Array
(
[0] => 1
[1] => 46
[2] => 6
)
You have to rename sid to sid[] and $_GET['sid'] will be an array:
http://codepad.org/rmfhwGA6
I don't think this will work, because you can't use the same GET parameter more than once. If you use it more than once, it will overwrite the previous value.
You could create your own separator char.
URL:
sids=1*2*3*4*5
Parsing:
<?php
$sidArray = explode('*', $_GET['sids']);
?>
use jsonencode on an array and send the values using jquery get and jsondecode on the receiving end, i would also recoment urlencode and urldecode functions

Why am I getting an array of SimpleXMLElement Objects here?

I have some code that pulls HTML from an external source:
$doc = new DOMDocument();
#$doc->loadHTML($html);
$xml = #simplexml_import_dom($doc); // just to make xpath more simple
$images = $xml->xpath('//img');
$sources = array();
Then, if I add all of the sources with this code:
foreach ($images as $i) {
array_push($sources, $i['src']);
}
echo "<pre>";
print_r($sources);
die();
I get this result:
Array
(
[0] => SimpleXMLElement Object
(
[0] => /images/someimage.gif
)
[1] => SimpleXMLElement Object
(
[0] => /images/en/someother.jpg
)
....
)
But when I use this code:
foreach ($images as $i) {
$sources[] = (string)$i['src'];
}
I get this result (which is what is desired):
Array
(
[0] => /images/someimage.gif
[1] => /images/en/someother.jpg
...
)
What is causing this difference?
What is so different about array_push()?
Thanks,
EDIT: While I realize the answers match what I am asking (I've awarded), I more wanted to know why whether using array_push or other notation adds the SimpleXMLElement Object and not a string when both arent casted. I knew when explicitly casting to a string I'd get a string. See follow up question here:Why aren't these values being added to my array as strings?
The difference is not caused by array_push() -- but by the type-cast you are using in the second case.
In your first loop, you are using :
array_push($sources, $i['src']);
Which means you are adding SimpleXMLElement objects to your array.
While, in the second loop, you are using :
$sources[] = (string)$i['src'];
Which means (thanks to the cast to string), that you are adding strings to your array -- and not SimpleXMLElement objects anymore.
As a reference : relevant section of the manual : Type Casting.
Sorry, just noticed better answers above, but the regex itself is still valid.
Are you trying to get all images in HTML markup?
I know you are using PHP, but you can convert use this C# example of where to go:
List<string> links = new List<string>();
if (!string.IsNullOrEmpty(htmlSource))
{
string regexImgSrc = #"<img[^>]*?src\s*=\s*[""']?([^'"" >]+?)[ '""][^>]*?>";
MatchCollection matchesImgSrc = Regex.Matches(htmlSource, regexImgSrc, RegexOptions.IgnoreCase | RegexOptions.Singleline);
foreach (Match m in matchesImgSrc)
{
string href = m.Groups[1].Value;
links.Add(href);
}
}
In your first example, you should:
array_push($sources, (string) $i['src']);
Your second example gives an array of strings because you are converting the SimpleXMLElements to strings using the (string) cast. In your first example you are not, so you get an array of SimpleXMLElements instead.

Categories