Passing nested PHP loop to javascript - javascript

I have a PHP array that looks like this:
([NAME] => Array ( [0] => 16 [1] => 12 [2] => 4 [3] => 0 ))
([NAME2] => Array ( [0] => 19 [1] => 19 [2] => 0 [3] => 0 ))
([NAME3] => Array ( [0] => 31 [1] => 29 [2] => 2 [3] => 0 ))
This array is generated by PHP by pulling data from a database.
(The array is much larger than this, but for simplicity, I only included 3 records)
I really need this data to be usable in a script that generates a bar graph. For now, I only need the name and the first record. So, for example, in PHP
<?=$array['NAME'][0]?>
<?=$array['NAME2'][0]?>
would echo the information I need from each, but I'm not sure how to put that into the format I need into javascript.
This is the javascript format that I need:
{ tech: 'NAME', value: $array['NAME'][0] },
{ tech: 'NAME2', value: $array['NAME2'][0] },
{ tech: 'NAME3', value: $array['NAME3'][0] },
{ tech: 'NAME4', value: $array['NAME4'][0] },
...etc
Some type of loop would be preferred because the names can vary.
If it was just PHP I could do it, but I'm not too fluent in Javascript.
Could someone help me come up with a solution?

The good news is that you don't have to know much javascript. Create your data structure as you want it in php, and then use json_encode: http://php.net/manual/en/function.json-encode.php
<?php
$for_chart = array();
foreach($names as $key => $name){
$obj = new stdClass;
$obj->tech = $key;
$obj->value = $name[0];
$for_chart[] = $obj;
}
?>
the result is:
[{"tech":"NAME","value":1},{"tech":"NAME2","value":5},{"tech":"NAME4","value":9}]
You can use it in your javascript like this:
<script>
var my_names = <?=json_encode($for_chart)?>;
alert(my_names[0].value); // alerts "1"
</script>
http://sandbox.onlinephpfunctions.com/code/2682f09fd5515b220402db9c600b70a0501a87d9

If you json_encode the array you have, it comes out to:
{"NAME1":[16,12,4,0],"NAME2":[19,19,0,0],"NAME3":[31,29,2,0]}
which will give you a javascript object to iterate:
If you have the json object in a variable called arrayData:
var gridData = [];
for (var name in arrayData) {
var rowObj = { tech: name, value: arrayData[name][0] };
gridData.append(rowObj);
}
At the end of that, you will have an array of objects that should be what you're looking for in gridData.

If you would echo it in the following format you can JSON to get the data:
[{tech: 'NAME', value: $array['NAME'][0]},{tech: 'NAME', value: $array['NAME'][0]}]
In your js you could do something like the following:
var names = $.getJSON('http://localhost/index.php?name', function(data) {});
This way you have an array in js.

To get the javascript code just iterate over the php array an echo the json records like you want:
<?= foreach($array as $key => $value){
echo "{ tech: '" .$key ."', value: '" .$value[0] ."'},";
}
?>

//Assuming this is your array
$getArray["NAME"] = array(16,12,4,0);
$getArray["NAME2"] = array(19,19,0,0);
$getArray["NAME3"] = array(31,29,2,0);
$newArray = array();
foreach($getArray as $indKey=>$indArrVal) {
$newArray[] = array("tech"=>$indKey, "value"=>$indArrVal[0]);
}
echo json_encode($newArray);
here it is, create a new array, with the required indexes and then stringify it using json_encode

Related

regex pattern for json array and dynamic multi-level array check

On the page there will be about several hundred elements to which individual keywords are assigned, as in a kind of index.
These keywords are used to dynamically show or hide these elements with JavaScript, depending on whether the searched keywords are found. The keywords are inserted by PHP into the data-tags of the individual elements.
For example, the keyword directory could look like this:
$keywords =
[
'MainCategory1' =>
[
'Category1' =>
[
'Value1' => 0,
'SubCategory1' => [
'Value2' => 0,
'Value3' => 0
]
],
'Category2' =>
[
'Value4' => 0,
'Value5' => 0
]
],
'MainCategory2' =>
[
'Category2' =>
[
'Value2' => 0,
'Value4' => 0
],
'Category3' =>
[
'Value5' => 0,
'Value6' => 0
]
]
];
Some categories and values may occur more than once, depending on which subtopic they are in.
For example, an element has been assigned these keywords:
MainCategory1 > Category1
MainCategory1 > Category2 > Value5
MainCategory2 > Category2 > Value2
The keywords are stored in the backend as a json string and written to the data attributes. For this element:
{"MainCategory1":{"Category1":0,"Category2":{"Value5":0}},"MainCategory2":{"Category2":{"Value2":0}}}
My idea now is to loop through all elements as soon as a keyword is selected and see if the stored JSON string matches "MainCategory1 > Category2 > Value5".
This would correspond in PHP to
isset($keywords['MainCategory1']['Category2']['Value5'])
My questions about this:
How could I make the isset query dynamic in php if I don't know beforehand how many levels the keyword has? This is important for when a keyword is set, to check in the backend whether the keyword is valid at all. I could loop through each level though; is there an alternative for this?
What I'm doing so far:
$arrayString = explode(' > ', $array);
$foundCount = 0;
$currentArray = $keywords;
for($i = 1; $i <= count($arrayString); $i++) {
$key = $arrayString[$i - 1];
$keyExists = array_key_exists($key, $currentArray);
if(!$keyExists)
break;
$currentArray = $currentArray[$key];
$foundCount++;
}
$isKeywordValid = $foundCount == count($arrayString);
I am familiar with regex, but I am having trouble finding a pattern that solves this problem. What does the pattern have to look like if I want to know if "MainCategory1 > Category2 > Value5" matches the JSON string in this particular example? (This convention is only a paraphrase for the different levels. The string can also be parsed differently)
Taken from How to access and manipulate multi-dimensional array by key names / path?, you can walk down the structure using a reference:
function array_isset($path, $array) {
$path = explode(' > ', $path);
$temp =& $array;
foreach($path as $key) {
if(!isset($temp[$key])) { return false; }
$temp =& $temp[$key];
}
return true;
}
Or turn MainCategory1 > Category2 > Value5 into ["MainCategory1"]["Category2"]["Value5"] and evaluate it as an isset:
function array_isset($path, $array) {
$path = '["' . str_replace(' > ', '"]["', $path) . '"]';
eval("return isset(\$array{$path});");
}
Then just do:
if(array_isset('MainCategory1 > Category2 > Value5', $keywords)) {
// code
}

Fetch file and convert JavaScript array into PHP array

I've been searching for a few days now, trying to figure out the best way to solve a problem: I want to fetch a JavaScript file from e.g. GitHub and convert a JavaScript array into PHP.
My first idea was to fetch the page (raw.githubusercontent.com) with PHP (file_get_contents) on server side and then parse it. But it's a multidimensional array, so I think this is complicated and not very flexible.
Example
In JavaScript only the keys are relevant (e.g. https://raw.githubusercontent.com/xxx/example.js)
var cars = {
'Saab': {
'Blue': true,
'Green': true,
...
},
'Volvo': {
'Brown': true
},
'BMW': {
'Black': true
},
...
}
In PHP the content should be combined as a string array:
Array
(
[0] => 'SaabBlue'
[1] => 'SaabGreen'
[2] => 'VolvoBrown'
[3] => 'BMWBlack'
...
)
I would be happy if someone had an idea a short hint ;)
Update:
I think I will do this server side with PHP.
$arr = array();
// fetch the file
$content = file_get_contents('https://raw.githubusercontent.com/xxx/example.js');
// remove all comments and unnecessary lines with RegEx
$content = preg_replace(<RegEx Expression>, '', $content);
foreach(preg_split("/((\r?\n)|(\r\n?))/", $content) as $line){
// filter with strpos and/or preg_match
// [x][ ][ ]
if ( filter ) {
$m = explode("'", $line);
// [ ][x][ ]
} else if ( anyfilter) {
$n = explode("'", $line);
// [ ][ ][x]
} else if ( filter ){
$o = explode("'", $line);
$str = $m[1] . $n[1] . $o[1];
array_push($arr, $str);
}
}
Set all the variables into cookies.
document.cookie = "cars_Saab_Blue="+cars.Saab.Blue;
Do something similar (dpending on the situation) and set everything into 1 or more cookies.
Now by using $_COOKIE['cars_Saab_Blue'] you can get the cookie and use it wherever you want,

PHP Array key value next to each other to use in javascript

i need to create chart based on php array and i found something about traversing in stackoverflow posts but those answers doesnt help for converting this:
Array
(
[product sample 1] => Array
(
[0] => Array
(
[hitsTotal] => 63
)
[1] => Array
(
[hitsTotal] => 113
)
)
[product sample 2] => Array
(
[0] => Array
(
[hitsTotal] => 57
)
[1] => Array
(
[hitsTotal] => 107
)
)
)
to
['product sample 1', 63, 113],
['product sample 2', 57, 107]
how to convert?
Assuming $input is the array you present in your post you can do the following:
$output = array();
foreach($input as $key => $value)
{
$obj = array();
$obj[] = $key;
$obj[] = $value[0]['hitsTotal'];
$obj[] = $value[1]['hitsTotal'];
$output[] = $obj;
}
var_dump($output); //This will print it on screen so you can validate the output
To prepare your data for passing to js(client side) as an array of arrays use the following approach (array_walk, array_column, array_merge and json_encode functions):
// supposing that $arr is your initial array
$result = [];
array_walk($arr, function($v, $k) use(&$result){
$hitsTotals = array_column($v, 'hitsTotal');
$result[] = array_merge([$k], $hitsTotals);
});
echo json_encode($result);
The output:
[["product sample 1",63,113],["product sample 2",57,107]]

how to convert array from php into js

I have this array value: print_r ($array); which contains 2 data (this is latt and long of my gmap project).
The array is from:
<?php
if(isset($_GET['q'])) {
$q = $_GET['q'];
}
$q = isset($_GET['q']) ? $_GET['q'] : '';
$array = array();
$nsUser="SELECT * FROM cliententry WHERE kampusterdekat=:q";
$uQuery = $mydb->prepare ($nsUser);
$uQuery->execute(array(':q' => $q));
while ($result = $uQuery->fetch(PDO::FETCH_ASSOC)) {
$id=$result['id'];
$googlemap=$result['googlemap'];
//echo $googlemap;
$array[] = $googlemap;
print_r ($array);
}
?>
When I echo, the result will be like this:
Array
(
[0] => -5.364000343425874, 105.24465411901474
)
Array
(
[0] => -5.364000343425874, 105.24465411901474
[1] => -5.362878747789552, 105.24150252342224
)
Point:
What I need is to make the result into this format:
var wwwsitus = [
['<h4>area</h4>', wwwsitus[0]],
['<h4>area</h4>', wwwsitus[1]],
];
where locations (<h4>area</h4>) are removed. So, it must be, as follows:
var wwwsitus = [
[...,...],
[...,....],
];
Note:
Since I've no capable about array in JS, please help me to fix my title based on my issue. Thks in adv.

php array to javascript format?

I have an array.
Array
(
[0] => Array
(
[title] => Badminton Men's Singles Gold Medal Kashyap Parupalli
[mp4] => http://www.tensports.com/media/video/kashyap.mp4
[webm] => http://www.tensports.com/media/video/kashyap_VP8.webm
[playThumb] => {filedir_2}Kashyap_medal.jpg
[videoPoster] =>{filedir_3}Kashyap_medal.jpg
)
[1] => Array
(
[title] => Boxing Men's Welter (69kg) Silver medal: Mandeep Jangra
[mp4] => http://www.tensports.com/media/video/MandeepJangraMedal.mp4
[webm] => http://www.tensports.com/media/video/MandeepJangraMedal_VP8.webm
[playThumb] => {filedir_2}Mandeep_Jangra_medal.jpg
[videoPoster] =>{filedir_3}Mandeep_Jangra_medal.jpg
)
)
I am trying to convert it in a object like below.
Javascript Format required :
videos = [
{
src : [
'http://www.tensports.com/media/video/kashyap_VP8.webm',
'http://www.tensports.com/media/video/kashyap.mp4'
],
poster : '{filedir_2}Kashyap_medal.jpg',
title : "Badminton Men's Singles Gold Medal Kashyap Parupalli"
},
{
src : [
'http://www.tensports.com/media/video/MandeepJangraMedal.mp4',
'http://www.tensports.com/media/video/MandeepJangraMedal_VP8.webm'
],
poster : '{filedir_2}Mandeep_Jangra_medal.jpg',
title : "Boxing Men's Welter (69kg) Silver medal: Mandeep Jangra"
}
];
what I have done :
var videoObject = $.parseJSON(<?php echo $js_VideoURL ?>);//where $js_VideoURL = json_encode($above-array);
$.each(videoObject, function(key, value) {
console.log('stuff : ' + key + ", " + value);
});
It's giving me error.I am uncertaing about getting the data in required format.Any help?
The format you're expecting in javascript is not compatible with the php array you've given.
Going from there I am assuming that is the problem, since you didn't give the exact error message you're encountering. From what I can gather you're missing a piece of PHP to put the video's in the correct format. To solve that you can do the following:
Note the comments in the code, they should explain what is going on.
PHP:
// $videos is assumed to be the array you've given in your question
$arr = [];
foreach ($videos as $video) {
// Create video object
$obj = new stdClass;
$obj->src = [
$video['webm'],
$video['mp4']
];
$obj->poster = $video['playThumb'];
$obj->title = $video['title'];
$arr[] = $obj;
}
// $arr is now the output you would need for processing
Javascript:
var videoObject = <?php echo $js_VideoURL ?>; //where $js_VideoURL = json_encode($arr);
$.each(videoObject, function(key, value) {
console.log('stuff : ' + key + ", " + value);
});
Edit:
Your first mistake is as Quentin mentioned that you're putting the json directly into javascript, which means it will be interpreted as a native javascript object. I missed that in my original answer.
It means you indeed do not need to use $.parseJSON to get the object you want. I changed my answer to reflect that.
Note:
Your code implies that you have Javascript snippets in your php / html templates. This is considered bad practice, and can be resolved with relative ease.
What you could do is put the json in a data attribute of the relevant html element on the page (escape the json before printing) then picking up the json string using jQuery on initialization with
var object = $element.data('json');
Using this (jQuery will automatically try parse the string as json) it will be ready for use.
The JSON format is a subset of JavaScript literal syntax
json_encode outputs JSON (which, if just dumped in JS, will be treated as a literal)
parseJSON takes a string of JSON and converts it to a data structure
Therefore: Don't use parseJSON as it will force the object you have into a string ("[Object object]") and then try to parse that as JSON.
Just:
var videoObject = <?php echo $js_VideoURL ?>;
Come on.. did you even check PHP docs, or even google json encode!?!?!
var videoObject = <?php echo json_encode($js_VideoURL); ?>;

Categories