How to split array and store each value in localstorage - javascript

I have array like below,
Array
(
[0] => http://192.168.1.156/dutees_dev/image/catalog/tmprgbimages/1508911570.png
[1] => http://192.168.1.156/dutees_dev/image/catalog/tmprgbimages/1508911570.png
[2] => http://192.168.1.156/dutees_dev/image/catalog/tmprgbimages/1508911571.png
)
I want to split above array and each key value has to stored in localStorage like 'front'=> array[0],'back'=>array[1],'side'=>array[0].
How to achieve this. ?

If your array is in JAVASCRIPT, you can access to the array elements directly, so you can call the localStorage function directly...
var yourArray = [
'http://192.168.1.156/dutees_dev/image/catalog/tmprgbimages/1508911570.png',
'http://192.168.1.156/dutees_dev/image/catalog/tmprgbimages/1508911570.png',
'http://192.168.1.156/dutees_dev/image/catalog/tmprgbimages/1508911571.png'
];
localStorage.setItem('front',yourArray[0]);
localStorage.setItem('back',yourArray[1]);
localStorage.setItem('side',yourArray[2]);
If your array is in PHP, you'll have to add a <script> element...
<?php
$yourarray = array(
"http://192.168.1.156/dutees_dev/image/catalog/tmprgbimages/1508911570.png",
"http://192.168.1.156/dutees_dev/image/catalog/tmprgbimages/1508911570.png",
"http://192.168.1.156/dutees_dev/image/catalog/tmprgbimages/1508911571.png"
);
?>
<script>
localStorage.setItem('front','<?=$yourarray[0]?>');
localStorage.setItem('back','<?=$yourarray[1]?>');
localStorage.setItem('side','<?=$yourarray[2]?>');
</script>

you can have separate script (test.php) and have a json out as below
<?php
$arr1 = array(
0 => 'http://192.168.1.156/dutees_dev/image/catalog/tmprgbimages/1508911570.png',
1 => 'http://192.168.1.156/dutees_dev/image/catalog/tmprgbimages/1508911570.png',
2 => 'http://192.168.1.156/dutees_dev/image/catalog/tmprgbimages/1508911571.png'
);
$arr2 = array('front'=>'', 'back'=>'', 'side'=>'');
// assign values from array 1 to array 2
$arr2['front'] = $arr1[0];
$arr2['back'] = $arr1[1];
$arr2['side'] = $arr1[2];
echo json_encode($arr2);
then from javascript you can access this object as follows and store it in local storage
<script>
$(document).ready(function () {
$.get("test.php", function (data, status) {
var out = JSON.parse(data);
// Store in local storage
localStorage.setItem("frontElem", out.front);
localStorage.setItem("backElem", out.back);
localStorage.setItem("sideElem", out.side);
var side = localStorage.getItem("sideElem", out.side);
console.log(side)
});
});
</script>

Related

Create javascript array which have the same structure with php array

In the sever side i have an array with structure like that:
array ('_1489378560544_544' => array (
'customer_group_id' => '0',
'permission_id' => 'disable_products_price',),
'_1489740032764_764' => array (
'customer_group_id' => '',
'permission_id' => '',),)
So now in the client side i want to create an javascript array with the same structure to server side. Is there any possible way to do that?
So after i got all data separately how can i organize my array look like this
var arr = [{_1489378560544_544 : [customer_group_id : 0 , permission_id : 'permission_id'] }]
Here is my javascript get data function:
$('#category_permission > tbody > tr').each(function() {
var id = $(this).attr("id");
var customer_group_id = $(this).children('td:first').children('select:first').val();
var permission_id = $(this).children('td:nth-child(2)').children('select:first').val();
});
Thanks for your help.
You can use json_encode to convert your PHP array to a JSON string and use JSON.parse() to obtain the equivalent Javascript object. Take a look here: https://www.w3schools.com/js/js_json.asp
Something like this :
var arr = [{_1489378560544_544 : [customer_group_id : 0 , permission_id : 'permission_id'] }]
in your php view file
jsStr = '<?php echo json_encode($array)?>'
jsObj = JSON.parse(jsStr);
console.log(jsObj.keyname);
like that all keys can be accessed to get the value. javascript don't support alphanumerical keys for array.
Answer from #Mistalis should help.

Call array from php

If i want to call an array from php into typescript also in an array form how i can do it
this is my php code :
$AccessQuery = "SELECT name,lastname,phone,email
FROM user
INNER JOIN access ON id
WHERE id
$userQuery = mysqli_query($localhost, $AccessQuery) or trigger_error(mysql_error(), E_USER_ERROR);
while ($AccessQueryRow = mysqli_fetch_assoc($userQuery)) {
$AccessData[] = array(
'id' => $AccessQueryRow['id'],
'code' => $AccessQueryRow['code'],
);
};
$arr = array(
"user_access_details" => $AccessData,
);
echo json_encode($arr);
I try this in order to encoded and use each one as a variable in an array
var jsonData = JSON.parse(data);
what i really want is how i can put each menu_id in an array field :
arr= {id1,id2}
the same for the code
how i can put each menu_id in an array field : arr= {id1,id2}
If you only care about the ids, ignore the code values. Get the array of the shape you want in PHP.
while ($AccessQueryRow = mysqli_fetch_assoc($userQuery)) {
$AccessData[] = $AccessQueryRow['id'];
};
echo json_encode($AccessData);
On the client side:
var jsonData = JSON.parse(data);
The result will be the array of just ids.

Associative php array sent via jquery returns [Object object]

I have to pass a php multidimensional array via ajax/jQuery to another php file.
I have encoded the array using
I expected theat every item in the array would have been an array itself. Instead it returns [Object object].
How can I access the data using php?
here's my code:
in the first php file:
<script type="text/javascript">
var arr_data = <?php echo json_encode($itemsData); ?>;
$("#confirmButton").click(function(){
$.post("send_test.php", {"my_array_data[]":my_array_data}, function( data ) {
alert(data);
});
});
</script>
the other php file:
<?php
$my_array_data = $_POST['my_array_data'];
?>
if I try to retrieve the first row ($my_array_data[0]) I get [Object object]
I just want to access to $my_array_data[0]['category'] etc.
A couple of errors here:
the data you are passing to ajax has an incorrect key using brackets[]
you are not passing the correct object through ajax since my_array_data is never defined
redo your code like this:
PHP
$itemsData = array(
array(
"test" => 30,
"test2" => 10,
),
array(
"test" => 90,
"test2" => 50,
)
);
JS
var arr_data = <?php echo json_encode($itemsData); ?>;
$("#confirmButton").click(function () {
$.post("send_test.php", {my_array_data: arr_data}, function (data) {
console.log(data);
});
});
Then in send_test.php
$data = $_POST['my_array_data'];
print_r($data);
Result:
Array
(
[0] => stdClass Object
(
[test] => 30
[test2] => 10
)
[1] => stdClass Object
(
[test] => 90
[test2] => 50
)
)
You're putting json-encoded data into the arr_data javascript variable - however you don't appear to be sending that to the other php file.
In the other php file, try using json_decode on the data you're receiving in the POST request:
$my_array_data = json_decode($_POST['my_array_data']);
Yes, as Aric says, name array consistently like this:
var my_arr_data = <?php echo json_encode($itemsData); ?>;

how to make this javascript object from php json encode

hello i am trying to figure out how i would ago about pulling information from a database in php and json_encoding it ito a JavaScript object that contains several JavaScript arrays that themselves have children objects and arrays.
below is the JavaScript i need. ive been playing with embedding arrays into php objects but cant seem to get it to come our correctly.
self.navigation = [
{
menutext:"Home",
url:"/"
},
{
menutext:"About",
url: "#/about",
submenu:[
{
menutext:"Pricing",
url: "/pricing"
}
]
}
];
<script type="text/javascript">
var jsObject = <?php echo json_encode($phparray); ?>;
</script>
pretty self-explanatory i think, if you need the object a specific way it's about how you format your php array itself.
To get arrays within objects you use the object key and set it to an array like so:
$phpArray = array(
'magic' => array('elmo')
);
json_encoded an array will be within the "magic" object. In order to get the parent item as an array with objects inside i would just fudge it in the variable setting itself like so:
<script type="text/javascript">
var jsObject = [<?php echo json_encode($phparray); ?>];
</script>
To get submenu into array have you tried the following:
$phpArray = array(
'menutext' => 'About',
'url' => '#/about',
'submenu' => array(
array(
'menutext' => 'Pricing',
'url' => '/pricing')
)
);
Bit unintuitive I know. Actually to get exactly what you want without fudging it would be:
$phpArray = array(
array(
'menutext' => 'Home'
),
array(
'menutext' => 'About',
'url' => '#/about',
'submenu' => array(
array('menutext' => 'Pricing',
'url'=> '/pricing')
)
)
);

Creating a JSON array starting with index 1

I need to create a JSON array starting with index 1
Here is my code which picks the images from the websites
$image_urls = array();
//get all images URLs in the content
foreach($get_content->find('img') as $element)
{
/* check image URL is valid and name isn't blank.gif/blank.png etc..
you can also use other methods to check if image really exist */
if(!preg_match('/blank.(.*)/i', $element->src) && filter_var($element->src, FILTER_VALIDATE_URL))
{
$image_urls[] = $element->src;
}
}
//prepare for JSON
$output = array('title'=>$page_title, 'images'=>$image_urls, 'content'=> $page_body);
echo json_encode($output); //output JSON data
data.images gives the array bu it starts with 0
Try
$output = array();
$output['1'] = array('title'=>$page_title, 'images'=>$image_urls, 'content'=> $page_body);
echo json_encode($output); //output JSON data
Output would be:
{"1":{"title":(*page_title*),"images":(*img_url*),"content":(*page_body*)}}
Try using array_unshift
$image_urls = array_unshift($image_urls,null);//add an element at the zeroth index
unset($image_urls[0]);//remove the zero index
An single line solution to the image_url array:-
$arr=array(1,2,3,4,5,6);
$arr = array_combine(range(1, count($arr)), $arr);
echo '<pre>';print_r($arr);
Output :
Array
(
[1] => 1
[2] => 2
[3] => 3
[4] => 4
[5] => 5
[6] => 6
)

Categories

Resources