My Jquery code
var attrid = [];
var attrvalue = [];
$.each($(".attname1"), function(index){
if($('.getval'+index+'').val() != undefined){
attrid.push($('.getval'+index+'').attr("id"));
attrvalue.push($('.getval'+index+'').val());
}
});
//outcome data
["5931", "5950", "5951", "5952"] //id
["cas", "bsd", "Canvas", "Grey"] //name
The result format that I actually want:
$ary = array (
[0] => array(
Id => 5931,
value=> cas,
),
[1] => array(
Id => 5950,
value=> bsd,
),
[2] => array(
Id => 5951,
value=> Canvas,
),
[3] => array(
Id => 5952,
value=> Grey,
)
);
Question:
Above code are using Jquery to loop the data and store into array, I'm trying to create loop to create the result format the I want, but I failed to do that,anyone can provide me some sample code or idea which is can using Jquery to create the results format that I provided.Thank you.
Make one array and push objects onto it:
var ary = [];
$('.attname1').each(function(index) {
var getval = $('.getval' + index);
if (getval.val()) {
ary.push({
id: getval.attr('id'),
value: getval.val()
});
}
});
Related
I have this function that required selected Ids into an array and the result is this
[7950, 7949, 7948, 7947, 7945, 7944, 7943, 7942, 7941, 7938]
But now I want to results to be formatted like [{id: 7950}, {id:7949}] etc
function
this.checked = this.students.filter((student) => student.checked === true).map((student) => student.id);
Simply return an object in your map function.
const arr = [7950, 7949, 7948, 7947, 7945, 7944, 7943, 7942, 7941, 7938].map(id => ({id}));
console.log (arr);
You could map objects with a short hand property.
var ids = [7950, 7949, 7948, 7947, 7945, 7944, 7943, 7942, 7941, 7938],
result = ids.map(id => ({ id }));
console.log(result);
This question already has answers here:
PHP json_decode integers and floats to string
(6 answers)
Closed 3 years ago.
I am trying to add multiple markers into a google map and i have found a way to do that here.
Now I have a json array response from the server as shown below.
// function to get user names and addresses
public function getUserAddresses(Request $request)
{
$users = User::where('address', '!=', null)->select('name', 'address')->get(); //this is a laravel query
$userData = [];
foreach ($users as $user) {
$userData[$user->name] = $user->address;
}
return $userData;
}
This code above is what gives me the response below.
{
"plumber1": "-1.2523238641713191,36.87899683074249",
"plumber2": "-1.2192245641713191,36.87899687428849",
"allan plumber": "-1.2192238641713191,36.87899683068849"
}
but for me to use this data it must be in these format as shown below in javascript.
[
["plumber1", -1.2523238641713191,36.87899683074249],
["plumber2", -1.2192245641713191,36.87899687428849],
["allan plumber", -1.2192238641713191,36.87899683068849]
];
You can use this php code
$str = '{
"plumber1": "-1.2523238641713191,36.87899683074249",
"plumber2": "-1.2192245641713191,36.87899687428849",
"allan plumber": "-1.2192238641713191,36.87899683068849"
}';
$array =json_decode($str);
$new_array = [];
foreach ($array as $key => $value) {
$coordinates = explode(',',$value);
$coordinate1 = (float) $coordinates[0];
$coordinate2 = (float) $coordinates[1];
$new_array[] = array($key,$coordinate1,$coordinate2);
}
print_r($new_array);
OUTPUT
Array
(
[0] => Array
(
[0] => plumber1
[1] => -1.25232386
[2] => 36.878996830742
)
[1] => Array
(
[0] => plumber2
[1] => -1.2192245641713
[2] => 36.878996874288
)
[2] => Array
(
[0] => allan plumber
[1] => -1.2192238641713
[2] => 36.878996830688
)
)
You can also check the demo here
Here is Javascript version
<script type="text/javascript">
var str = `{
"plumber1": "-1.2523238641713191,36.87899683074249",
"plumber2": "-1.2192245641713191,36.87899687428849",
"allan plumber": "-1.2192238641713191,36.87899683068849"
}`;
var obj = JSON.parse(str);
var array = [];
var counter =0;
for (var key in obj) {
var myarr = obj[key].split(",");
array[counter] = [key, parseFloat(myarr[0]), parseFloat(myarr[1])];
counter++
}
console.log(array);
</script>
Try json_decode
ini_set( 'precision', 17 );
$jsonToArray = json_decode($json, JSON_NUMERIC_CHECK);
I'm loosing hairs on this.
I have an PHP array:
Array
(
[10-10-2015] => Array
(
[0] => Array
(
[hour] => 10:00
[title] => Meeting x
)
)
[10-09-2015] => Array
(
[0] => Array
(
[hour] => 17:00
[title] => another meeting
)
[1] => Array
(
[hour] => 11:11
[title] => other meeting
)
)
)
As you can see, there are two meetings in the same day.
That's correct.
I need to generate Javascript array:
var codropsEvents = {
'10-16-2015': ['<span>event one</span>', '<span>event two</span>'],
'10-17-2015': ['<span>event one</span>', '<span>event two</span>'],
};
Any help or suggestions how to do it ?
Use json.
echo 'var myJsArray = JSON.parse("'.json_encode($myPhpArray).'");';
You can use json_encode($array) in php to convert it to valid json string. In your javascript you can use JSON.parse(json) for parsing json string.
For example :
<?php
$array=array
(
'10-10-2015' => array
(
0 => array
(
'hour' => '10:00',
'title' => 'Meeting x'
)
)
);
?>
<script>
var data = JSON.parse('<?php echo json_encode($array); ?>');
// or var data = <?php echo json_encode($array); ?>;
</script>
Try this approach:
create array that You want:
<?php
$events = .....;
$data = [];
foreach($events AS $date => $eventsByDate) {
$data[$date] = [];
foreach($eventsByDate AS $event) {
$data[$date][] = '<span>'.$event['title'].'</span>';
}
}
?>
output $data array encoded as json string and parse it to get javascript object or array:
<script>
var codropsEvents = JSON.parse('<?=json_encode($data)?>');
console.log(codropsEvents);
</script>
New progress...
Without JSON.parse, only just:
var codropsEvents = <?=json_encode($events);?>
it's returning
var codropsEvents = {
"10-10-2015":[
{"time":"10:00","title":"Meeting X"}
],
"10-09-2015":[
{"time":"17:00","title":"Other event"},
{"time":"11:11","title":"Other Meeting"}
]
}
which causes returning Object
Any ideas ?
I have the following URL:
http://mydomain/Forwards?searchValue[]=Nike+Webstore&searchValue[]=Bodyman&category_filter[]=Animals+%26+Pet+Supplies&category_filter[]=Fashion&country_filter[]=Aland+Islands&country_filter[]=American+Samoa
This url contains alot of paramters that are sent as an array:
Now i wish to get each individual array and its value out
in the above example the result should be something like this:
searchValue = array(
[0] = 'Nike Webstore'
[1] = 'Bodyman'
);
category_filter = array(
[0] = 'Animals & Pet Supplies'
[1] = 'Fashion'
);
country_filter = array(
[0] = 'Aland Islands'
[1] = 'American Samoa'
);
is it possible to get it out like this and if so how? i have attempted with the following:
decodeURIComponent(
(RegExp(name + '=' + '(.+?)(&|$)').exec(location.search)||[,null])[1]
However this only returned 1 value (Nike Webstore) in my example.
as parameters are an array. the below code will work just fine..
// our test url
var url ="http://mydomain/Forwards?searchValue[]=Nike+Webstore&searchValue[]=Bodyman&category_filter[]=Animals+%26+Pet+Supplies&category_filter[]=Fashion&country_filter[]=Aland+Islands&country_filter[]=American+Samoa" ;
// filtering the string..
var paramsList = url.slice(url.indexOf("?")+1,url.length) ;
var filteredList = paramsList.split("&") ;
// an object to store arrays
var objArr = {} ;
// the below loop is obvious... we just remove the [] and +.. and split into pair of key and value.. and store as an array...
for (var i=0, l=filteredList.length; i <l; i +=1 ) {
var param = decodeURIComponent(filteredList[i].replace("[]","")).replace(/\+/g," ") ;
var pair = param.split("=") ;
if(!objArr[pair[0]]) { objArr[pair[0]] = [] ;}
objArr[pair[0]].push(pair[1]);
}
console.log(objArr);
which will give us....
[object Object] {
category_filter: ["Animals & Pet Supplies", "Fashion"],
country_filter: ["Aland Islands", "American Samoa"],
searchValue: ["Nike Webstore", "Bodyman"]
}
hope this helps.. :D
Try to see if this pattern works for you
(?:\?|&)(.+?)=([A-Z+%0-9]+)
Example here
I'm having trouble to get the proper formatted texts of each child elements, either as an Array or in as text.
I had tried
var name= jQuery(".childOne").text();
var number = jQuery(".childTwo").text();
but it joins all the name/number text in name and number.
HTML is:
<span class="parent"><span class="childOne">David</span><span class="childTwo">541</span></span>
<span class="parent"><span class="childOne">Gruce</span><span class="childTwo">162</span></span>
<span class="parent"><span class="childOne">Proman</span><span class="childTwo">743</span></span>
and I need to generate output in multi-dim-array so that each child-element's-text can be figured out properly.
Preferred output can be in array or in any form.
Array
(
0 = > array (
0 => "David",
1 => "541"
),
1 = > array (
0 => "Gruce",
1 => "162"
),
2 = > array (
0 => "Proman",
1 => "743"
)
)
try this:
var data = [];
$('span.parent').each(function() {
var $this = $(this);
data.push({
'name' : $this.find('span.childOne').text(),
'number' : $this.find('span.childTwo').text()
});
});
BTW: jQuery uses the Sizzle selctor engine. You should define the element type before the class, like span.parent. This is much more faster.
If this is a fixed structure, you can do:
var data = [];
$('.parent').each(function() {
data.push({
'name': $(this).children('.childOne').text(),
'number': $(this).children('.childTwo').text()
});
});
I have made a working example
var array= [];
$('.parent').each(function(index) {
array.push({
'name': $(this).children('.childOne').text(),
'number': $(this).children('.childTwo').text()
});
});
alert(array[0].name);
$('.parent').each(function(index) {
alert($(this).find('.childOne').text());
alert($(this).find('.childTwo').text());
});
After you can put them into an array