Morning I'm working on a project and I have a issue, it's about to know how to remove duplicate entry from an array object .
Here is structure of my array :
"IDGROUP": [
{
"id": 72
},
{
"id": 72
}
]
Here is code snippet:
if($compteGroupes && $compteGroupes->getId()!=0){
$Tableaux_pack[$current_id_fictif]["ingroup"]]=
$Mes_comptes_reels_dependants [$taille_reel];
$Tableaux_pack[$current_id_fictif]["IDGROUP"]=
array(
'id'=>$compteGroupes->getId()
);
}
thank's for your help
Your object looks like a javascript object - what do you actually mean?
are the entries classes? are they arrays
do you want to filter nested/multidimensional arrays based on their values?
do you want to filter different class objects?
see here: https://stackoverflow.com/a/2426579/8548024
Related
I have a line of code similar to the following:
Sport::pluck('id', 'name)
I am dealing with frontend JavaScript that expects a list in this format:
var list = [
{ text: 'Football', value: 1 },
{ text: 'Basketball', value: 2 },
{ text: 'Volleyball', value: 3 }
...
]
I am trying to figure out how I can somehow transform the id and name values that I pluck from my model to a format similar to the Javascript list.
If that's unclear, I am looking to end up with an associative array that contains two keys: text and value, where text represents the name field on my model, and where value represents the id of the model - I hope this makes sense.
How would I approach this?
I initially tried something like this (without checking the documentation)
Sport::pluck(["id" => "value", "name" => "text]);
But that isn't how you do it, which is quite clear now. I've also tried some map-related snippet, which I cannot seem to Ctrl-z to.
Any suggestions?
Another method is to use map->only():
Sport::all()->map->only('id', 'name');
The purpose of pluck is not what you intend to do,
Please have a look at below examples,
Sport::selectRaw("id as value, name as text")->pluck("text","value");
// ['1' => 'Football', '2'=>'BasketBall','3'=>'Volleyball',...]
Syntax
$plucked = $collection->pluck('name', 'product_id');
// ['prod-100' => 'Desk', 'prod-200' => 'Chair']
Please see the documentation.
Your output is possible using simple code.
Sport::selectRaw('id as value, name as text')->get();
You could use map.(https://laravel.com/docs/5.8/collections#method-map)
$mapped = Sport::all()->map(function($item, $index) {
return [
"id" => $item["id"],
"name" => $item["text"]
];
});
This is the easiest way. Actually Laravel offers a better way for it. You can use api resources to transform your data from eloquent for the frontend:
https://laravel.com/docs/5.8/eloquent-resources
Try with toArray function:
Sport::pluck('id', 'name)->toArray();
Then you can return your result with json_encode php function;
I have a small issue. I have a json file which I fetch data from.
When I print_r() the data, I see the field I want. But trying to call them, only 2 on 3 works, one seems to not be fetch-able.
Here the code, if someone have an idea about what's wrong:
Original JSON :
[
{
"ņame": "Xcoin",
"rate": "100.0000",
"status": "online"
}
]
The JSON with print_r()
Array
(
[ņame] => XCoin
[rate] => 100.0000
[status] => online
)
When I fetch individually each fields:
echo $coin['name']."<br>";
echo $coin['rate']."<br>";
echo $coin['status']."<br>";
The result of the previous code:
100.0000
online
Like if the name was not there! How's possible? I have others array and name fetch correctly, using same format.
Look at your array keys: ņ !== n so you're referencing an array index that doesn't exist.
I.e., that is not an n in the JSON you're getting, it's one of these characters.
(TIL this thing is called a cedilla.)
Look it's other character
ņame != name
How can I query a MongoDB with array inside.
[{
"issuer":"34a8c528-11f9-490c-82ef-db94808ba4d8",
"dateAdded":1520547942137,
"duration":2147483647,
"reason":".",
"active":false,
"rank":"5569543b-efc4-4acf-b6b2-cafd3663b806",
"rankName":"Owner"
},{
"issuer":"34a8c528-11f9-490c-82ef-db94808ba4d8",
"dateAdded":1520556569443,
"duration":2147483647,
"reason":".",
"active":true,
"rank":"5569543b-efc4-4acf-b6b2-cafd3663b806",
"rankName":"Owner"
}]
I tried doing:
$result = $collection->find(array("groups.rankName" => "Owner"));
But it returns nothing. Any ideas?
How about $result = $collection->find(array("rankName" => "Owner"));?
By adding groups you're actively searching for an object with that, although I understand that you meant the whole objects containing your rankName property.
I'm struggling with the output of json_encode. I'm attempting to speed up our large dropdown navigation menu by storing everything in a json file that gets updated once a day and calling that when required.
I'm producing the json using json_encode, but it seems to be looping everything into additional, unneccessary, arrays and I can't figure out how to prevent this.
I've even tried fiddling with str_replace but had no success in generating valid json (though clearly this isn't really a long term solution in any case). I've also tried to figure out what combination of "each" I would need to get into the nestled arrays, but haven't found the right combination.
Below is the json I'm ending up with (I've reduced the number of entries to make it easier to see, the format is the same... just within each of Film, Gaming etc there are more items).
[
[
"Film",
[
{
"title": "13 Awkward Moments That Must Have Happened After The End Of Famous Movies",
"link": "http:\/\/whatculture.com\/film\/13-awkward-moments-that-must-have-happened-after-the-end-of-famous-movies.php",
"image": [
"http:\/\/cdn3.whatculture.com\/wp-content\/uploads\/2013\/08\/HP-100x60.jpg",
100,
60,
true
]
}
]
],
[
"TV",
[
{
"title": "10 Awesome TV Twists You Never Saw Coming",
"link": "http:\/\/whatculture.com\/tv\/10-awesome-tv-twists-you-never-saw-coming.php",
"image": [
"http:\/\/cdn3.whatculture.com\/wp-content\/uploads\/2013\/08\/lost-locke-100x60.jpg",
100,
60,
true
]
}
]
],
[
"Gaming",
[
{
"title": "WWE 2K14: Every Possible Classic Match",
"link": "http:\/\/whatculture.com\/gaming\/wwe-2k14-every-possible-classic-match.php",
"image": [
"http:\/\/cdn3.whatculture.com\/wp-content\/uploads\/2013\/08\/444-100x60.jpg",
100,
60,
true
]
}
]
]
]
And this is the script I'm using to generate said code:
I've included everything for completeness. A lot of the below is just the Wordpress query to pull back my relevant data:
$cats = array("Film","TV","Gaming","Sport","Music");
function filter_where($where = '') {
$where .= " AND post_date > '" . date('Y-m-d', strtotime('-3 days')) . "'";
return $where;
}
add_filter('posts_where', 'filter_where');
foreach($cats as $cat) {
$the_query = array(
'numberposts' => 5,
'category_name' => $cat,
'meta_key' => "visitcount",
'orderby' => "meta_value_num",
'suppress_filters' => false );
$special_query_results = get_posts($the_query);
foreach( $special_query_results as $post ) {
setup_postdata($post);
$myposts[] = array('title'=> html_entity_decode(get_the_title()),'link'=>get_permalink(get_the_ID()),'image'=>wp_get_attachment_image_src( get_post_thumbnail_id(get_the_ID()), 'smallthumb' ));
}
$pop_posts[] = array($cat,$myposts);
unset($myposts);
} // foreach cats as cat1000
wp_reset_postdata();
remove_filter('posts_where', 'filter_where');
$json_pop = json_encode($pop_posts,JSON_PRETTY_PRINT);
This is what I'm using to pull it back when user hovers on the nav item:
$.getJSON('http://whatculture.com/data/wc6.json', function(popular) {
$.each(popular.Sport, function() {
$('.popularMenu').append("<li><img src="+this.image[0]+" />"+this.title+"</li>");
});
});
This is a bit of a guess (see my comment regarding a need to clarify which arrays you see as "unnecessary") but the line that stands out to me is this:
$pop_posts[] = array($cat,$myposts);
This can be translated as "create a 2-element array, whose first member is $cat (the name of the category) and whose second member is $myposts (an array of posts); add this 2-element array as the last member of the array $pop_posts". The result is that $pop_posts is an array of two-element arrays.
Perhaps what you wanted to say was "set the key $cat of the associative array $pop_posts to the value $myposts (an array of posts)", which would be this:
$pop_posts[$cat] = $myposts;
That would make the resulting structure simpler, as instead of an array of 2-element arrays, you would have a single hash (PHP associative array, JS object) whose keys were categories, and whose values were the popular posts for that category.
However, there are two disadvantages:
It wouldn't work if the category names were not unique, since a key cannot exist more than once in a hash. I don't think this applies here.
JSON hashes (and the JS object they create) are unordered key-value collections. So if you want to preserve the order of your categories, you need a different mechanism (either the array-of-arrays you already have, or an additional array storing the "correct" order to visit the keys). In your example, you reference Sport specifically, so this may not be an issue.
I have this structure:
"_id": NumberInt(1),
"link_id": {
"1000748": {
"pi": NumberInt(34),
"li": NumberInt(8)
},
"1002836": {
"pi": NumberInt(21),
"li": NumberInt(1002836)
}
}
I want to make a query to select only the link_ids with a 'pi' => 34. I have tried in php $res = $collection->findOne(array("_id" => intval($_catids['categoryid'])), array("linkid.$.pi" => intval(34)));
No success. Any ideas? Thx a lot!
First off I recommend to use the MongoId object for the _id field, has a lot of options and a lot of usefull functions within it
But that did not answer the question, the query is as followed
{
"linked_id.pi": 34
}
Then you translated to PHP it is
array(
'linked_id.pi' => 34,
)
Then depening on the result you want you need to use find or findOne