I create this output with PHP:
foreach ($bk as $blink) {
$out["url"][] = $blink->url;
$out["anchor"][] = $blink->anchor;
}
$json = Zend_Json::encode($out);
echo ($json);
I want to receive and process the output with a $.ajax call.
Could you point me to a nice tutorial about multidimensional arrays with javascript/jquery or help me loop* through the json results? I got a bit confused with it.
I am trying to put those on a table, so I will be using <td>url-i</td><td>anchor-i</td> . This part, I figured out how. To put the correct values on url-i and anchor-i is the problem.
I would imagine the JSON output for that will be something like:
{'url': ['url1', 'url2', ... ],
'anchor': ['anchor1', 'anchor2', ... ]}
If that is the case, then they will be of equal length (and importantly equal indexes) and you can loop through one of the two using jQuery.each().
$.getJSON('jsonapp.php', function(data) {
$.each(data.url, function(index, url) {
var anchor = data.anchor[index];
$('#mytable').append('<tr><td>' + url + '</td><td>' + anchor +'</td></tr>');
});
});
I've not run that code, so it might have a few flaws, but that's the gist of it.
PHP can try to cast objects into arrays by itself, and for simple stuff, it usually works fine.
As for multidimensional arrays, Javascript isn't too different from most other higher-level programming/scripting languages when it comes to arrays. Really, any tutorial online on multidimensional arrays will do just fine. A multidimensional array is simply an array of arrays.
When you receive the string client-side, you just want to parse it. jQuery has its own method, but you can use JSON.parse. Afterwards, based on how you've set up your arrays, you'd want to do something like this.
<? $count = count($json_parsed['url']); for($i = 1; $i < $count; $i++) : ?>
<td><?=$json_parsed['url'][$i];?></td>
<td><?=$json_parsed['anchor'][$i];?></td>
<? endfor; ?>
This may be philosophically not the best way to do it though. If you have a whole bunch of objects and you want to make a table out of them, the best way would be to create an array of those objects as represented by associative arrays (sort of like hash tables in other programming languages). PHP natively tries to convert objects into associative arrays. I wouldn't be surprised if Zend_Json::encode does it automatically. If it does, you might want to pull simply:
echo Zend_Json::encode($bk);
If not, let me know, and we'll talk about how to do that.
You could have a look on any template frameworks, but for this exact case it seams useful to check one of those two: pure by beebole or jquery pure html templates.
Doing it by yourself might be tempting but why to reinvent the well - I know from my experience, that frameworks are about 2 times faster, then self made code.
Related
I'm a newbie in the PHP area, so please bear with my question.
Basically I have/will have a pretty big json file, and I need to query the file to get a single entry based on the key provided. An example would be as follow:
{
"key1" : {value1},
"key2" : {value2},
...,
"keyn" : {valuen}
}
I will need to retrieve only one value at any one request, and hope to get a better performance.
The basic way to deal with this sort of handling in PHP from my search is to use json_decode() and then foreach.
However, this approach seems like need to iterate through the whole file based on the order of the key and what the key I am looking for. So if I am looking for keyn, then essentially I have to read from top to bottom of the large file. (Yep, I can use some sort algorithm to get a better result)
But from my understanding, JSON is basically another form of HashMap, so given HashMap can get easily and fast, is there a similar way in PhP to get the best performance out of it?
Well, given the structure you provided you definitely don't need to loop through the entire object.
If you're looking for keyn, you would just do:
$obj = json_decode($input);
echo $obj->keyn;
Maybe I'm missing something obvious. If you want to prevent having to json_decode the entire object, your question makes a bit more sense though... but that's not what you're asking.
From JSON.org
JSON is built on two structures:
A collection of name/value pairs. In various languages, this is realized as an object, >record, struct, dictionary, hash table, keyed list, or associative array.
An ordered list of values. In most languages, this is realized as an array, vector, list, or >sequence.
You can't just interact with json without first using json_decode() to turn it into a usable object. But if you know the keys, after running json_decode() you can interact with it (because it's now an object). for example:
<?php
$string = '{"foo": "bar", "cool": "attr"}';
$result = json_decode($string);
// Result: object(stdClass)#1 (2) { ["foo"]=> string(3) "bar" ["cool"]=> string(4) "attr" }
var_dump($result);
// Prints "bar"
echo $result->foo;
// Prints "attr"
echo $result->cool;
?>
In situations like this, var_dump() and print_r() are your friends.
There really isn't any magical way to find the value without using any kind of loop
I haven't benchmarked this:
This is how I would approach the problem without having to finish the iterating over the whole tree if and when a match is foudn
$key = 'keyn'
$obj = json_decode(file_get_contents('path/to/your/file'), true);
$len = count($obj);
$match = false;
for($ii = 0; $ii < $len; $ii++){
$curr = $obj[$ii];
if($curr == $key) {
$match = $curr;
}
break;
}
In PHP you can use function: file_get_contents to parse JSON file. You have to go through each and every key-value pairs.
I would like to send an integer array with 30 values Integer[] temp = new Integer[30] over HTTP (POST) to PHP an get the data in PHP again. How can I do that? I know how to send a single value, like a string, but not how to send an array.
One way is to serialize the array in the way the php serialize command does it.
After receiving the string value(by the method you currently use), you can use the unserialize command to get the array in your php code.
Here is a litle php example to demonstrate the workflow.
$arr = array(1,2,3,4,5,6);
$stringArr = serialize($arr);
echo $stringArr;
echo "<br/>";
$arr2 = unserialize($stringArr);
if ($arr === $arr2)
{
echo "arrays are equal";
}
The output of the script is:
a:6:{i:0;i:1;i:1;i:2;i:2;i:3;i:3;i:4;i:4;i:5;i:5;i:6;}
arrays are equal
The main difficulty is to construct the resulting string for complex structures (in your case, it is pretty straight forward for an array of integers).
This fact results in the second approach.
One can use a serialization API or another notation than used by the php example.
As stated by the others, JSON is one of the widespread notations.
PHP also provides a possibility to serialize and unserialize json objects.
Simply use json_decode and look at the example in the manual.
can anyone explain the purpose of json_encode when doing a .post query.
This is what i often see in other's coding.
.post php script
...
...
echo json_encode($a);
I mean if i want to do a return from a .post script and returning an array via .post. Wouldn't i just need to do the following?
.post php script
...
...
$a = array("foo", "bar", "hallo", "world");
$string=implode(',',$a) in my php script
return $string;
javascript
$.post('$url',function(data){
data_arr=data.split(',');
//After which just get the values in the array
alert(data_arr[0]); //ALERTS 'foo'
alert(data_arr[1]); //ALERTS 'bar'
});
If anyone can just help by clearing this up for me and let me see the light for using json in this purpose, that would be great.
Perhaps its also due to my inept knowledge of JSON as well.
Would greatly appreciate it if anyone can advise me on why is it better to use JSON encode in this case and how am i suppose to use it via a .post request instead of just echoing out the string and split it later.
Thanks.
Using json_encode ensures that your data is always valid.
It doesn't really matter for simple data that you have control over, though imagine if someday you have a comma inside one of the values. With JSON encoded strings, you don't have to worry about an arbitrary separator token.
Also, with JSON you can easily encode Objects/Arrays without needing to reinvent the wheel.
First of all, in my opinion and practise, JSON syntax is fairly similar to Javascript objects and it's great when dealing with more complex data types that have to be sent/requested and parsed later on.
For example:
If you're doing a post request and you're serializing all the form fields which you validate server side (using PHP) you're most likely going to need to use key => value pairs like textbox_name => value. It's more logical to do it that way, than to select values by numeric indexes (what if the form layout changes?)
Example code using commas:
<?php
$array = array('Tom', 'Hanks', 'Football');
$string = join(',',$array);
echo $string; //it's obvious - the output is Tom,Hanks,Football
?>
The javascript that receives the string
$.post(url,{},function(data){
var values = data.split(',')
$("#name").text(values[0]);
$("#surname").text(values[1]);
$("#interests").text(values[2]);
});
So it makes sense right? But wouldn't it more sense to do this instead:
<?php
header('Content-type: application/json');
$array = array('name' => 'Tom', 'surname' => 'Hanks', 'interests' => 'Football');
echo json_encode($array);
?>
And the javascript:
$.post(url,{},function(data){
for(index in data) {
$("#"+index).text(data[index]);
}
//or
$("#name").text(data.name);
$("#surname").text(data.surname);
$("#interests").text(data.interests);
});
The same goes with parsing response data with Javascript. Having an object is more logical than having a CSV string.
Obviously it depends on the use case, but in general JSON gives you a logical structure of stringified Objects/Arrays which can be translated back into objects and arrays and looped through or manipulated in any way.
Also JSON is now a standard. Everyone uses it which means that it's not for no reason.
In other words - JSON data makes more sense.
What would you say is the most efficient way to get a single value out of an Array. I know what it is, I know where it is. Currently I'm doing it with:
$array = unserialize($storedArray);
$var = $array['keyOne'];
Wondering if there is a better way.
You are doing it fine, I can't think of a better way than what you are doing.
You unserialize
You get an array
You get value by specifying index
That's the way it can be done.
Wondering if there is a better way.
For the example you give with the array, I think you're fine.
If the serialized string contains data and objects you don't want to unserialize (e.g. creating objects you really don't want to have), you can use the Serialized PHP library which is a complete parser for serialized data.
It offers low-level access to serialized data statically, so you can only extract a subset of data and/or manipulate the serialized data w/o unserializing it. However that looks too much for your example as you only have an array and you don't need to filter/differ too much I guess.
Its most efficient way you can do, unserialize and get data, if you need optimize dont store all variables serialized.
Also there is always way to parse it with regexp :)
If you dont want to unseralize the whole thing (which can be costly, especially for more complex objects), you can just do a strpos and look for the features you want and extract them
Sure.
If you need a better way - DO NOT USE serialized arrays.
Serialization is just a transport format, of VERY limited use.
If you need some optimized variant - there are hundreds of them.
For example, you can pass some single scalar variable instead of whole array. And access it immediately
I, too, think the right way is to un-serialize.
But another way could be to use string operations, when you know what you want from the array:
$storedArray = 'a:2:{s:4:"test";s:2:"ja";s:6:"keyOne";i:5;}';
# another: a:2:{s:4:"test";s:2:"ja";s:6:"keyOne";s:3:"sdf";}
$split = explode('keyOne', $storedArray, 2);
# $split[1] contains the value and junk before and after the value
$splitagain = explode(';', $split[1], 3);
# $splitagain[1] should be the value with type information
$value = array_pop(explode(':', $splitagain[1], 3));
# $value contains the value
Now, someone up for a benchmark? ;)
Another way might be RegEx ?
The reason I am asking this question is because I have landed my first real (yes, a paid office job - no more volunteering!) Web Development job about two months ago. I have a couple of associates in computer information systems (web development and programming). But as many of you know, what you learn in college and what you need in the job site can be very different and much more. I am definitely learning from my job - I recreated the entire framework we use from scratch in a MVC architecture - first time doing anything related to design patterns.
I was wondering what you would recommend as the best way to pass/return values around in OO PHP? Right now I have not implement any sort of standard, but I would like to create one before the size of the framework increases any more. I return arrays when more than 1 value needs to get return, and sometimes pass arrays or have multiple parameters. Is arrays the best way or is there a more efficient method, such as json? I like the idea of arrays in that to pass more values or less, you just need to change the array and not the function definition itself.
Thank you all, just trying to become a better developer.
EDIT: I'm sorry all, I thought I had accepted an answer for this question. My bad, very, very bad.
How often do you run across a situation where you actually need multiple return values? I can't imagine it's that often.
And I don't mean a scenario where you are returning something that's expected to be an enumerable data collection of some sort (i.e., a query result), but where the returned array has no other meaning that to just hold two-or-more values.
One technique the PHP library itself uses is reference parameter, such as with preg_match(). The function itself returns a single value, a boolean, but optionally uses the supplied 3rd parameter to store the matched data. This is, in essence, a "second return value".
Definitely don't use a data interchange format like JSON. the purpose of these formats is to move data between disparate systems in an expected, parse-able way. In a single PHP execution you don't need that.
You can return anything you want: a single value, an array or a reference (depending on the function needs). Just be consistent.
But please don't use JSON internally. It just produces unnecessary overhead.
I also use arrays for returning multiple values, but in practice it doesn't happen very often. If it does, it's generally a sensible grouping of data, such as returning array('x'=>10,'y'=>10) from a function called getCoordinates(). If you find yourself doing lots of processing and returning wads of data in arrays from a lot of functions, there's probably some refactoring that can be done to put the work into smaller units.
That being said, you mentioned:
I like the idea of arrays in that to pass more values or less, you just need to change the array and not the function definition itself.
In that regard, another technique you might be interested in is using functions with variable numbers of arguments. It is perfectly acceptable to declare a function with no parameters:
function stuff() {
//do some stuff
}
but call it with all the parameters you care to give it:
$x = stuff($var1, $var2, $var3, $var4);
By using func_get_args(), func_get_arg() (singular) and func_num_args() you can easily find/loop all the parameters that were passed. This works very well if you don't have specific parameters in mind, say for instance a sum() function:
function sum()
{
$out = 0;
for($i = 0; $i < $c = func_num_args(); $i++) {
$out += func_get_arg($i);
}
return $out;
}
//echoes 35
echo sum(10,10,15);
Food for thought, maybe you'll find it useful.
The only thing I'm careful to avoid passing/returning arrays where the keys have "special" meaning. Example:
<?php
// Bad. Don't pass around arrays with 'special' keys
$personArray = array("eyeColor"=>"blue", "height"=>198, "weight"=>103, ...);
?>
Code that uses an array like this is harder to refactor and debug. This type of structure is better represented as an object.
<?php
Interface Person {
/**
* #return string Color Name
*/
public function getEyeColor();
...
}
?>
This interface provides a contract that the consuming code can rely on.
Other than that I can't think of any reason to limit yourself.
Note: to be clear, associative arrays are great for list data. like:
<?php
// Good array
$usStates = array("AL"=>"ALABAMA", "AK"="ALASKA", ... );
?>