explode new line in javascript - php

How do I convert the php code below into javascript? I google it and found something to do with st.replace(/,/g,"\n") but how to apply it to the variable? I have low knowledge about javascript and trying to learn it.
$items = explode("\n", $model);

The answer is:
items = model.split("\n")

No, you are searching for [String].split("\n") which returns an Array. The replace you found would be similiar to implode("\n", explode(",", $model)).

The basically equivalent code is:
var model = 'some string...';
var items = model.split('\n');

var yourArray = [];
var yourString = 'a,b,c,d,e';
yourArray = yourString.split(',');

Related

JSON array unset

First of all, I really don't know if that kind of topic exist. But I searched a lot and now I am here.
My question about parsing. For example I would like to unset some items.
$now = array();
$now[0]['name'] = "Hello1";
$now[0]['si'] = "BumBum1";
$now[1]['name'] = "Hello2";
$now[1]['si'] = "BumBum2";
$now[2]['name'] = "Hello3";
$now[2]['si'] = "BumBum3";
$now[3]['name'] = "Hello4";
$now[3]['si'] = "BumBum4";
echo json_encode($now)."<br>";
unset($now[0]);
echo json_encode($now);
And the output:
[{"name":"Hello1","si":"BumBum1"},{"name":"Hello2","si":"BumBum2"},{"name":"Hello3","si":"BumBum3"},{"name":"Hello4","si":"BumBum4"}]
{"1":{"name":"Hello2","si":"BumBum2"},"2":{"name":"Hello3","si":"BumBum3"},"3":{"name":"Hello4","si":"BumBum4"}}
And my the JSON file turns to messy code. Appears numbers and etc.
Any ideas how to solve this.
You need to "reindex" the array (use array_values() function).
//unset..
unset($now[0]);
//reindex
$now = array_values($now);
//display as before
echo json_encode($now);

Using array_push to add elements to array

I have an array & I'd like to add data to the array using PHP. I can't add it directly.
How would I do this using array_push?
<script type="text/javascript">
var parks = [{"title":"Football Park","lat":"55.86234","lng":"-4.250635999999986","img":"icon.png"}]
</script>
You can try:
//if your JSON string on server side <--PHP-->
$park = json_decode([{"title":"Football Park","lat":"55.86234","lng":"-4.250635999999986","img":"icon.png"}],true);
$park['key'] = 'someValue';
$newJSON = json_encode($park);
// if your JSON string on client side <--JS-->
var parkObj = JSON.parse(park);
parkObj.key = 'someValue';
console.log(JSON.stringify(parkObj));
//[{"title":"Football Park","lat":"55.86234","lng":"-4.250635999999986","img":"icon.png","key" : "someValue"}]
I found http://www.php.net/manual/en/function.array-merge.php and feel this will do the job for me - thanks for your input.

not receiving JSON from php with getJSON

I am trying to pass an array to the browser using php and jquery but I the when I try to use the 'data' returned from php's encode_json, it comes up undefined. I'm just learning php, jquery, and json and so far haven't found very good documentation on alot of this stuff, especially json, even in the books I have. Thanks in advance!
Here is a stripped down version of the jquery I have
$(document).ready(function(){
var jsonResult;//I will want to be able to use the data in other functions
$.getJSON("json.php", function(data){
jsonResult = data;
var str;
var nuts = [203,204,205,207];
str = '<p>' + data[nuts[0]].NutraDesc + '</p>';
$('#stuff').html(str);
}
);
});
This is the php:
include_once 'databasePHP.php';
$json_tst = $db->query( "SELECT def.Nutr_No, NutrDesc, Nutr_Val, Units
FROM nutr_def as def JOIN nut_data as data ON def.Nutr_No = data.Nutr_No
WHERE data.NDB_No = 1001 LIMIT 0, 2");
$food = array();
while($row = $json_tst->fetch(PDO::FETCH_ASSOC))
{
$Nutr_No = $row['Nutr_No'];
$food[$Nutr_No][] = array(
'NutrDesc' => $row['NutrDesc'],
'Nutr_Val' => $row['Nutr_Val'],
'Units' => $row['Units']
);
};
echo json_encode($food);
?>
which returns this json which I checked on jsonlint.com and it said it was valid:
{"203":[{"NutrDesc":"Protein","Nutr_Val":"0.85","Units":"g"}],"204":[{"NutrDesc":"Total lipid (fat)","Nutr_Val":"81.11","Units":"g"}]}
It probably doesn't work because the numbers should be strings. Try to add quotes around the numbers in nuts, like this:
var nuts = ["203","204","205","207"];
The following probably works as well:
str = '<p>' + data[String(nuts[0])].NutraDesc + '</p>';
Also, have you tried adding console.log(data); to the getJSON function to make sure it receives the JSON?
EDIT:
Here is a working JSFiddle from your code:
http://jsfiddle.net/rKLqM/
Things that were wrong:
you weren't parsing the result as JSON (JSON.parse)
NutraDesc was spelled wrong
You didn't convert the numbers to strings
You needed to add [0] to the jsonResult because there's an extra array within it (see the [])
In Javascript object property can be accessed with obj["propName"]
So, change
var nuts = [203,204,205,207];
to
var nuts = ["203","204","205","207"];

AS3 equivalent of PHP key array

Hey all, title may be abit misleading but i didnt know the correct way to write it.
Basically, how can i do the AS3 equivalent of this php code:
return array('x' => 0, 'y' => 0);
The standard way of doing it is like this. The main thing to remember is that 'Object' in AS3 is almost equivalent to PHP's associative array's.
var obj:Object = {x:0, y:0};
trace(obj['x']); // like in PHP
trace(obj.x); // also valid
// AS3 version of foreach in PHP
for(var key:String in obj) {
trace(key +" = " + obj[key]);
}
private var map:Dictionary = new Dictionary();
map["x"] = 0;
map["y"] = 0;
You can do something like this
var myArray:Array = new Array({x:'0'},{y:'1'},{x:'2'});
or
var myArray:Array = new Array({x:'0',y:'1'},{a:'1',b:'2'});

Explode in jquery with php

I've got a jquery script, which creates a h3 tag and print a variable called result.tbUrl to it. I'd like to explode the variable at "::" and use the 2nd piece.
This is my method.
var link = document.createElement('h3');
link.innerHTML = <?php $link = "result.tbUrl"; $linkpiece = explode("::", $link); echo $pieces[1]; ?>;
Could you tell me please where did i make a mistake?
The first problem is, you're echoing $pieces[1], but exploding your string into $linkpiece which is a different variable.
However, you have a more serious problem: You're setting $link to the string "result.tbUrl". The string doesn't contain the delimiter '::', so exploding it has no effect and $linkpiece will be set to array(0 => 'result.tbUrl'). The line echo $linkpiece[1] will fail regardless, as there is nothing at index 1.
If result.tbUrl is a JavaScript variable, you cannot mix it with server-side PHP this way. You'll have to explode the variable client-side, in JavaScript:
var parts = result.tbUrl.split('::');
link.innerHTML = parts[1];

Categories