PHP equivalent to filter js - javascript

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"));

Related

How to remove double quotes from a JSON response in javascript? [duplicate]

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);

Extract values from JSON

I have the below JSON string. The id-dashes in the file are not optional unfortunately, neither is the syntax. I would like to extract the "dd" values with JavaScript/Node.
{
"a-id":{
"b-id":"random",
"bb-id":"random",
"bbb-id":"random",
"bbbb-id":{
"c":[
{
"d":"random",
"dd":"This_info_is_needed"
},
{
"d":"random",
"dd":"This_info_is_needed"
},
{
"d":"random",
"dd":"This_info_is_needed"
},
{
"d":"random",
"dd":"This_info_is_needed_2"
}
]
},
"bbbbb-id":"random",
"bbbbbb-id":"random"
}
}
I would be open to use any additional helper like lodash, jQuery, etc.
The output should be an array with: This_info_is_needed and This_info_is_needed_2.
Thank you in advance.
You can create custom function that will search your data deep and return value if key is dd using for...in loop.
var obj = {"a-id":{"b-id":"random","bb-id":"random","bbb-id":"random","bbbb-id":{"c":[{"d":"random","dd":"This_info_is_needed"},{"d":"random","dd":"This_info_is_needed"},{"d":"random","dd":"This_info_is_needed"},{"d":"random","dd":"This_info_is_needed"}]},"bbbbb-id":"random","bbbbbb-id":"random"}}
function getDD(data) {
var result = []
for(var i in data) {
if(i == 'dd') result.push(data[i])
if(typeof data[i] == 'object') result.push(...getDD(data[i]))
}
return result
}
console.log(getDD(obj))
If you just interested in the values only, can also just do this:
var obj = {"a-id":{"b-id":"random","bb-id":"random","bbb-id":"random","bbbb-id":{"c":[{"d":"random","dd":"This_info_is_needed"},{"d":"random","dd":"This_info_is_needed"},{"d":"random","dd":"This_info_is_needed"},{"d":"random","dd":"This_info_is_needed"}]},"bbbbb-id":"random","bbbbbb-id":"random"}};
var desiredResults = obj['a-id']['bbbb-id']['c'].map(function(data){return data.dd});
console.log(desiredResults);

Filter an array by value in nested arrays

I want to return the values of array if its values contains a specific string
var names= [
["FCFEDA", "Moon Glow"],
["FCFFE7", "China Ivory"],
["FCFFF9", "Ceramic"],
["FD0E35", "Torch Green"],
["FD5B78", "Wild Watermelon"],
["FD7B33", "Crusta Green"]
];
var color_swatches = [];
var result = $.grep(names, function(v,i) {
if(v[1].indexOf("Green") > -1){
return v[0];
}
})
color_swatches.push(result);
alert(color_swatches);
results in
FD0E35, Torch Green,FD7B33, Crusta Green
I want exactly like this
["#FD0E35","#FD7B33"]
Take note that the result should inside the square brackets and with qoutes. Only contains hex not the equivalent name and # added.
Any ideas?
You could try something like this.
var names= [
["FCFEDA", "Moon Glow"],
["FCFFE7", "China Ivory"],
["FCFFF9", "Ceramic"],
["FD0E35", "Torch Green"],
["FD5B78", "Wild Watermelon"],
["FD7B33", "Crusta Green"]
];
var color_swatches = [];
names.forEach(item => {
if(item[1].indexOf("Green") > -1){
color_swatches.push('#' + item[0]);
}
});
console.log(color_swatches);
console.log(JSON.stringify(color_swatches));
The .grep() function «Finds the elements of an array which satisfy a filter function» reference
In other words, in your code it returns the "sub-array" into result.
Try using a simple loop like this:
var names= [
["FCFEDA", "Moon Glow"],
["FCFFE7", "China Ivory"],
["FCFFF9", "Ceramic"],
["FD0E35", "Torch Green"],
["FD5B78", "Wild Watermelon"],
["FD7B33", "Crusta Green"]
];
var color_swatches = [];
for(i=0;i<names.length;i++){
if(names[i][1].indexOf("Green") > -1){
color_swatches.push( names[i][0] );
}
}
//color_swatches.push(result);
console.log(JSON.stringify(color_swatches));
Notice that I used JSON.strignify() only to see the content of the color_swatches array in console.
You could use a map function to transform the color_swatches array. In the map function, you can pick the first item and add a #. Before the alert, add:
color_swatches = $.map(color_swatches[0], function(index, color_swatch) {
return "#" + color_swatch[0];
});
You can use the JavaScript functions Array#filter, Array#map and String#includes:
var names = [
["FCFEDA", "Moon Glow"],
["FCFFE7", "China Ivory"],
["FCFFF9", "Ceramic"],
["FD0E35", "Torch Green"],
["FD5B78", "Wild Watermelon"],
["FD7B33", "Crusta Green"]
]
console.log(names.filter(n => n[1].includes('Green')).map(n => `#${n[0]}`))
// ["#FD0E35","#FD7B33"]

Convert array from php to javascript

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.

How do I convert PHP JSON to JS array

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;
});

Categories