I have array from database with json_encode, like this :
"[{"uid":"595e7d","name":"Elephant"},{"uid":"701b03","name":"Bird"},{"uid":"29a8c","name":"Lion"}]"
but how to make the array just display the record not with the field/column name, when i show in javascript like this :
javascript array :
{
"595e7d": "Elephant",
"701b03": "Bird",
"29a8c": "Lion"
}
whether it should be done in php or javascript?
thankyou
Handle with javascript:
function transfrom (arrs){
return arrs.reduce((init, arr) => {
init[arr.uid] = arr.name
return init
}
, {})
}
//usage
let arrs = [{"uid":"595e7d","name":"Elephant"},{"uid":"701b03","name":"Bird"},{"uid":"29a8c","name":"Lion"}]
transfrom(arrs)
// {595e7d: "Elephant", 701b03: "Bird", 29a8c: "Lion"}
Or you can handle it with PHP:
<?php
$arr = array (
array('uid' =>"595e7d", "name"=>"Elephant"),
array("uid" =>"701b03", "name" =>"Bird"),
array("uid" =>"29a8c", "name" =>"Lion")
);
function transform($v1, $v2) {
$v1[$v2["uid"]] = $v2["name"];
return $v1;
}
echo json_encode(array_reduce($arr, "transform", array()));
// {
// "595e7d": "Elephant",
// "701b03": "Bird",
// "29a8c": "Lion"
// }
?>
If I understood it correctly, you are looking for something like
var arr = [{"uid":"595e7d","name":"Elephant"},{"uid":"701b03","name":"Bird"},{"uid":"29a8c","name":"Lion"}];
var out = {};
arr.forEach(function(obj){
var tempArr = Object.values(obj);
out[tempArr[0]] = tempArr[1];
});
console.log(out);
Please note that the code is not too generic and may require modification based on your actual requirement.
Related
I'd like to translate this code in PHP:
let example = [
{id:'1', name:'abc', type:'123'},
{id:'2', name:'def', type:'345'},
{id:'3', name:'ghi', type:'678'},
{id:'4', name:'lmn', type:'901'}];
let res = example.filter(x => x.type != '901' && Number(x.id)>=2);
But I don't know the equivalent function of JS's filter; i found array_filter but only for simple array, not array of objects
you can filter $array like this:
function not_901($var)
{
return $var != 901;
}
print_r(array_filter($array, "not_901"))
Edit:
If you want the translation of your code in PHP here it is:
<?php
$example = [
['id'=>'1', 'name'=>'abc', 'type'=>123],
['id'=>'2', 'name'=>'def', 'type'=>345],
['id'=>'3', 'name'=>'ghi', 'type'=>678],
['id'=>'4', 'name'=>'lmn', 'type'=>901]
];
function not_901($var)
{
return $var['type'] != 901;
}
print_r(array_filter($example, "not_901"));
I have reference array which has values ["a","b","c","d"] .and i have another array which is obtaining as part of API which is not very consistent format .i am pointing some examples below
case 1.`{
names : ["a"],
value : [ [0],[0],[2],[4],... ]
}`
case 2. `{
names : ["a","c"],
value : [ [0,2],[0,0],[2,3],[4,4],... ]
}`
the result could be in any combination
but my requirement is to assign the value of incoming result into another array
having index same as my reference array
for example : in
case 1
`
let finalArray = [["0",null,null,null],
["0",null,null,null],
["2",null,null,null].... ]
`
for case 2:
`let finalArray = [["0",null,"2",null],
["0",null,"0",null],
["2",null,"3",null].... ]
`
alse attaching a fiddle with my inputs below
jsfiddle link to problem
any suggestions?
i am trying to use minimal for loops for performance optimization
Hope this will be helpful.
var refArray = ["a","b","c","d"];
setTimeout(()=>{processResult({
"names" : ["a"],
"value" : [ [0],[0],[2],[4]]
})},2000);
setTimeout(()=>{processResult(
{
"names" : ["a","c"],
"value" : [ [0,2],[0,0],[2,3],[4,4]]
})},4000);
setTimeout(()=>{processResult(
{
"names" : ["d","c"],
"value" : [ [0,2],[0,0],[2,3],[4,4]]
})},6000);
function processResult (result) {
let res = result.value;
let resArray = res.map((el)=>{
let k=Array(refArray.length).fill(null);
refArray.forEach((e,i)=>{
let indx = result.names.indexOf(e);
if(indx>=0){
k[i] = el[indx]
}
});
return k;
})
console.log("result",resArray)
}
Below is what I could think of that would require least iterations.
var refArray = ["a", "b", "c", "d"];
setTimeout(()=>{processResult({
"names" : ["a"],
"value" : [ [0],[0],[2],[4]]
})},2000);
setTimeout(()=>{processResult(
{
"names" : ["a","c"],
"value" : [ [0,2],[0,0],[2,3],[4,4]]
})},4000);
setTimeout(()=>{processResult(
{
"names" : ["d","c"],
"value" : [ [0,2],[0,0],[2,3],[4,4]]
})},6000);
function processResult(result) {
//This map will contain max names matched in the result
var maxItemsFromResult = {};
//Find the indexes in refArray and fill map
//e.g. 1st- {0:0}, 2nd - {0:0, 1:2}, 3rd - {0:3, 1:2}
result.names.forEach((item, index) => {
let indexFound = refArray.indexOf(item);
if (indexFound > -1) {
maxItemsFromResult[index] = indexFound;
}
});
//for performance if no key matched exit
if (Object.keys(maxItemsFromResult).length < 1) {
return;
}
//This will be final result
let finalArray = [];
//Because finalArray's length shuld be total items in value array loop through it
result.value.forEach((item, itemIndex) => {
//Create a row
let valueArray = new Array(refArray.length).fill(null);
//Below will only loop matched keys and fill respective position/column in row
//i'm taking all the matched keys from current value[] before moving to next
Object.keys(maxItemsFromResult).forEach((key, index) => {
valueArray[maxItemsFromResult[key]] = item[index];//get item from matched key
});
finalArray.push(valueArray);
});
console.log(finalArray);
return finalArray;
}
I want to find strings that has data from the strings from the array 2 in the array1 and save result as separate uniq array.
As can you see I search for not exact values. From the array1 values I know only part of the information, and I want to find the complete strings, with that information, in array1. And at the end I want to save what I found. So, I don't have a problem with finding here, but a problem with saving in the valid single JSON.
Array examples:
Array #1:
{
"overflow": [
"id:address:name:location:email",
...
"id2:address2:name2:location2:email2"
]
}
Array #2:
[
"location:email",
...
"location2:email2"
]
Code:
resultArr: function() {
var arr1 = '/var/log/1.json';
var arr2 = '/var/log/2.json';
var arrResult = '/var/log/result.json';
var arr2Obj = JSON.parse(fs.readFileSync(arr2, 'utf-8'));
for (var i = 0; i < arr2Obj.length; i++) {
var arr1Obj = JSON.parse(fs.readFileSync(arr1, 'utf-8'));
arr1Obj.overflow = arr1Obj.overflow.filter(function(e) {
return e.includes(arr2Obj[i])
});
fs.appendFile(arrResult, JSON.stringify(arr1Obj, null, 2), 'utf-8');
}
}
My result:
[{
"overflow": [
"id:address:name:location:email"
]
}{
"overflow": [
"id54:address54:name54:location54:email56"
]
}{
"overflow": [
"id2:address2:name2:location2:email2",
"id6:address6:name6:location2:email2"
]
}
What I really want:
{
"overflow": [
"id:address:name:location:email",
"id54:address54:name54:location54:email56",
"id6:address6:name6:location2:email2",
"id2:address2:name2:location2:email2"
]
}
Instead of reading the file again and again, and appending to the result repeatedly, just do both actions only once. All the rest should happen in memory.
You will also get better results (no risk for duplicates in result) when you swap the loops: put the filter action as the outer loop. For the inner loop you can use some, since one match is enough for the entry to be included:
resultArr: function() {
var arr1 = '/var/log/1.json',
arr2 = '/var/log/2.json',
arrResult = '/var/log/result.json',
arr2Obj = JSON.parse(fs.readFileSync(arr2, 'utf-8')),
arr1Obj = JSON.parse(fs.readFileSync(arr1, 'utf-8'));
arr1Obj.overflow = arr1Obj.overflow.filter(function(e) {
return arr2Obj.some(function (f) {
return e.includes(f)
});
});
fs.writeFileSync(arrResult, JSON.stringify(arr1Obj, null, 2), 'utf-8');
}
At each iteration, you're creating a new object and appening it to a file.
JSON is not a good format to append to.
You're replacing the array instead of adding fields to it.
You can do it that way, it should work :
resultArr: () => {
let arr1 = '/var/log/1.json';
let arr2 = '/var/log/2.json';
let arrResult = '/var/log/result.json';
let arr2Obj = JSON.parse(fs.readFileSync(arr2, 'utf-8'));
let arr1Obj = JSON.parse(fs.readFileSync(arr1, 'utf-8')); // reading only one time
arr1Obj.overflow = arr2Obj.map(value => {
return arr1Obj.overflow.filter(e => return e.includes(value))
});
fs.writeFileSync(arrResult, JSON.stringify(arr1Obj, null, 2), 'utf-8'); //Writing only one time
}
Array.map() executes the closure for each field in your array and group all the values returned by the closure in another array.
I also replaced some keywords to make your code more ES6 compliant. I you really want to append, you should use CSV and not JSON.
Good day,
I have this data which I got from my query on PHP its is currently a JSON Format, now I want to convert it into array so I can use it on my pdf. How can I do this?
so in order for me to use it on my javascript I used
var inventory = <?php echo json_encode($inventory); ?> ;
my JSON data :
var inv = [
{"xid":96,"xitem":"CARBOCISTEINE 500MG CAP (MYREX) BOX",
"itemId":852,
"price":3,
"mprice":3
},
{"xid":253,"xitem":"CIPROFLOXACIN 500MG TAB (PROSELOC\/FLAMINGO)",
"itemId":1165,
"price":0,
"mprice":0
}];
I tried
var rows = <?php echo json_encode($inventory); ?> ;
var arr = $.map(rows, function(el) { return el; });
and
when I console.log(arr);
I still get the object structure not the array structure that I wanted.
I also tried
var result = [];
for(var i in rows)
result.push([i, rows [i]]);
console.log(result);
but it gives me
[ ["0",Object { xid=96,xitem="CARBOCISTEINE 500MG CAP (MYREX) BOX",itemId=852,price=3,mprice=3}],
["1",Object{etc..}]];
instead
I want it to have a structure like
[96,"CARBOCISTEINE 500MG CAP (MYREX) BOX",852,3,3],
[253,"CIPROFLOXACIN 500MG TAB (PROSELOC\/FLAMINGO)",1165,0,0]
Is there something I am missing on my code or How should I be able to do this? thanks..
You can use this:
var arr = inv.map(function (obj) { return [obj.xid, obj.xitem, obj.itemId, obj.price, obj.mprice]})
console.log(arr);
If you do small changes to your map callback function, then it will be fine.
you can do just
class MyClass
{
public $var1 = 'value 1';
public $var2 = 'value 2';
public $var3 = 'value 3';
}
$class = new MyClass();
$arr = [];
foreach($class as $key => $value) {
$arr[] = $value;
}
echo json_encode($arr); //here's to check
in PHP - you can make a collection of object like this and iterate first oveer this collection to get result as you wanted to have
You shouldn't have to hard code the keys. The following works:
var arrayFromObject = inv.map(function (item) {
var arr = [];
for (var p in item) arr.push(item[p])
return arr;
});
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