How to Access Array - php

I am still a beginner in PHP and MySQL and have come across a complicated array I need some help with.
So far the arrays I have worked with are fairly flat, i.e. 1 row of data with multiple fields, say for example a result based on a single address, so line1, line2, line3, town, etc.
I am now dealing with an external api that returns the following results in xml
{"result":
{
group1 [{"fieldname1":"fieldresult1", "fieldname2":"fieldresult2}]
group2 [{"fieldname3":"fieldresult3", "fieldname4":"fieldresult4}]
}
"message":"OK",
"success":true}
My question is how do I access each of the results,
I am planning on using a foreach statement, and will be calling the result $xmlarray.
I then want to define strings such as $field1, $field2, but not sure how to do this when it seems to be quite a deep array, I am guessing something like:
$field1 = $array([0]["field2"];
As I say, I need someones help just to give me a brief overview here, thanks

This content of you posted Data looks like JSON to me...
so you could try some like
$json = json_decode($array);
than you could go for
$field1 = $json['group1']['fieldname1'];
and so on.
source

This is not XML. It is json. Use json_decode() for this.
$data = json_decode($response); //$response is the response you are getting from the api.
var_dump($data);
$data will contain the response. The you can access them easily.json_decode()

Related

struggling to understand JSON Parsing via PHP

not sure what I'm doing wrong here but i have my Json string and I'm trying to get the values to print out in the IF statement
i.e:
63,52,55
here is my code:
$jayjay = '{"items":{"cID":"63","qty":"2"},"items":{"cID":"52","qty":"1"},"items":{"cID":"55","qty":"1"}}';
echo $jayjay;
$obj = json_decode($jayjay, TRUE);
for($i=0; $i<=count($obj['items']); $i++) {
echo $obj['items'][$i]['cID'];
echo ",";
}
but the output is just blank and i cant figure out why
Any help would be appreciated.
Thank you
The problem is that you have key "items" multiple time in your JSON which is wrong. Please note that JSON key must be unique for well formed JSON.
Basically there is no error if you use more than one key with the same name, but in JSON, the last key with the same name is the one that is gonna be used. In your case, the key "items" would be better to contain an array of objects as it's value:
{'items' : [{"cID":"63","qty":"2"}, {"cID":"52","qty":"1"}, {"..." : "..."}]}
As Hamish stated in his comment, you can't have json as you've supplied. The keys (which is items in this case) are going to overwrite each other until the last key.
What I suggest is if you create an array like this:
{"items":[{"cID":"63","qty":"2"}, {"cID":"52","qty":"1"},.....]}
Allowing you to itterate as you require.
Meaning you can simply loop as you require:
$items = json_decode($json, true);
foreach($items as $thing){
echo $thing['cID'];
echo ",";
}
As has already been pointed out, your JSON data is malformed.
But since Stack Overflow is a rather inefficient method of syntax checking your data, I would suggest using a JSON linter (such as this one) on static JSON data in the future. Or at the very least, checking the return value of json_last_error after parsing to look for potential problems at least when testing or debugging.

JSON Stringify - PHP json_decode

I am new to JSON,ofr a project of my own I need to send array of objects to the server. Basically, I have a Question object, which has a couple of properties, like question, optionA, optionB etc. I have an array of Question objects.
example:
qArray = new Array();
qArray.push(new Question("where do you live?", "England", "ıtaly", "Usa");
I am adding a lot of questions objects to this array and in the end, I need to send this array to the server, like this:
$.post("backend-stuff/aj-save-test.php", { testName : $("#testName").val().toString(), 'questions' : JSON.stringify(qArray)}, function(result){
alert(result);
});
}
In PHP, I use this,
$questions = json_decode($_POST["questions"]);
$testName = $_POST["testName"];
Problem is that I cant read data, either I am sending it in the wrong way or whats wrong is on the php side.
Thank you for answers, I checked Google before sending the question, so please forgive me if this is so easy but for me its not so.
To convert stdClassObject to an array, check out get_object_vars().

How to merge some static data with json encode mysql array data?

I am trying to merge a static data with json encode array data for output. Here is my php code:
$arr = array();
$rs = mysql_query("SELECT id, name, picture, mail, gender, birthday FROM users WHERE id='$logged_id' ");
while($obj = mysql_fetch_object($rs)) {
$arr[] = $obj;
}
echo '{"users":'.json_encode($arr).'}';
Now I want to merge other data with it:
$user_ip = array("user_ip" => $user_ip_address);
I have tried array_merge($arr, $user_ip). But it didn't work. I think this is not correct json array format if I merge with existing data array. Please let me know what to do how to output other data as well as current data coming from mysql with json encode.
I am getting such output with my existing code, which is correct:
{"users":[{"id":"14","name":"Sonu Roy","picture":"image012.jpg","mail":"myemail#gmail.com","gender":"Male","birthday":"1983-01-11"}]}
But now I want to add other variable e.g $user_ip_address as user's data joining with current output data like this:
{"users":[{"id":"14","name":"Sonu Roy","picture":"image012.jpg","mail":"myemail#gmail.com","gender":"Male","birthday":"1983-01-11",user_ip:"127.0.0.1"}]}.
I want to get it in this way. How to do it? Please let me know. Thanks in advance.
try this:
echo json_encode(array('users' => $arr, 'user_ip' => $user_ip_address));
on a side note:
you should use PHP PDO class to connect and query the database.
mysql_fetch_object returns an object, not an array. So, what are you doing by $arr[] = $obj; is just adding an object into an array. So, the actual structure of the $arr is something like
$arr => [
[0] => Object(....),
[1] => Object(....),
....
]
In your particular case, I assume you are fetching single row by primary key, so there are only one object.
THe simpliest way to fix this is to add a field to an object. I haven't worked with PHP since 5.3, so can't be sure, but it's as simple as adding
$obj->user_ip = $user_ip_address;
inside the loop.
Btw, a couple of questions for you:
Why do you use loop if it should result in a single row?
Why you are embedding the variable directly into SQL query. It's quite vulnerable, read about sql-injections and how to prevent it (one day I was really tired telling people here on SO to use PDO and prepared statements, so just go read about it),
Have you read the documentation about mysql_fetch_object and array_merge? Why not (because if you have read it you wouldn't be asking the question).
Tried debugging? E.g. attaching a debugger and watching for variables contents? Inserting logging or (God forgive me) debug print with echo?
"Didn't work" is a quite bad error description. This time you was lucky, because the error was obvious. Next time, please, be more specific.

build SQL statement from json encoded string php

Welcome Stackoverflow nation ! I'm trying to decode json encoded string into SQL statement withing php.
Lets say I've such a json encoded string =>
$j = '{"groupOp":"AND","rules":[{"field":"id","op":"cn","data":"A"},{"field":"i_name","op":"cn","data":"B"}]}';
I want to build SQL WHERE clause (needed for filterToolbar search in jqGrid), something like this => "WHERE id LIKE %A% AND i_name LIKE %B% " and etc.
I've done this =>
$d = json_decode($j);
$filterArray = get_object_vars($d); // makes array
foreach($filterArray as $m_arr_name => $m_arr_key){
// here I can't made up my mind how to continue build SQL statement which I've mentioned above
}
Any ideas how to do that , thanks preliminarily :)
The first problem is you will want to pull out the groupOp operator.
Then, you have an object and inside that you have an array of objects, so you may want to look at the results of filterArray as that won't have the value you want.
Then, when you loop through, you will want to do it with an index so you can just pull the values out in order.
You may want to look at this question to see how you can get data out of the array:
json decode in php
And here is another question that may be helpful for you:
How to decode a JSON String with several objects in PHP?
There is an answer with an implementation for the server-side php code here
Correction: I had to unescape double-quotes in the 'filters' parameter to get it working:
$filters = str_replace('\"','"' ,$_POST['filters']);

How to search through POSTed form values using regex and return results

I'm working on a project where all of the members and their info are stored in a JSON file. I'm in the process of creating a search form and I need help on how to iterate through the members and check to see if there's an exact match or a similar match.
The members are stored in a SESSION variable:
$_SESSION['members'] = json_decode($jsonFile);
but I'm uncertain how to use regex to check for matches that are similar (and not just exact). For example, if a member's name is "Jonathan", I'd like that result to be returned even if the user searches "Jon". Is regex the correct approach? Any help will be greatly appreciated - thank you!
-Manoj
I think I'd be using a database to store the data rather than JSON so that you can use the LIKE searches, e.g.
SELECT * FROM users WHERE name LIKE 'Jon%'
If you absolutely have to use JSON you could loop through all members and use a regexp like
preg_match('/^'.$term.'.*/i', $element, $matches);
to check them all.
If the $jsonFile contents is an array of some sort, you may find preg_grep() of use, though it doesn't work on multidimensional arrays. You might have have to loop over each individual member record and grep the relevant fields yourself, something like:
foreach ($_SESSION['members'] as $idx => $member) {
... match relevant fields...
}

Categories