How to get a list of unique properties from object - php

I have an array of objects with a 'category' property. I need to get a list of the different categories, how can I do this given that I have a method to get the category from the object? Shown below creates a list of all the categories in the array, but obviously has lots of repeated categories:
foreach (getSourceCodes() as $source) {
echo $source->getCategory();
}

You can use array_unique() in php.
$categories = array();
foreach (getSourceCodes() as $source) {
array_push($categories, $source->getCategory());
}
$categories = array_unique($categories);
If categories is multidimensional, then use this method to serialise it, then get unique array and then change it back to array.
$categories = array_map("unserialize", array_unique(array_map("serialize", $categories)));

If you use the category as an array key, it will be unique by definition.
foreach (getSourceCodes() as $source) {
// The value is irrelevant. You can use a counter if you want to keep track of that.
$an_array[$source->getCategory()] = true;
// The key is just overwritten for duplicate values of getCategory()
}
// Then you can use array_keys to get the keys as values.
var_dump(array_keys($an_array));

Not sure what format your list is in but assumed comma separated values...
$aCategories = array();
$aList = array();
foreach (getSourceCodes() as $source) {
// Get categories as comma separated string list???
$sList = $source->getCategory();
// Convert string list to array
$aTmpList = explode(",",$sList);
//Check temp list against current list for new categories
$aDiffList = array_diff($aList,$atmpList);
//Merge new categories into current list
$aList = array_merge($aDiffList,$aList);
}
// Convert array to string list
$sCategories = implode(",", $aList);

Related

How can i remove the key which contain the value white space in PHP, Laravel?

public function store(Request $request)
{
$article = Article::create($request->only(['content']));
$categories = explode(",",$request->get('categories'));
$category_ids =[];
foreach ($categories as $category) {
$category_db = Category::where('name', trim($category))->firstOrCreate(['name'=> trim($category)]);
$category_ids [] = $category_db->id;
}
$article->category()->attach($category_ids);
return response("Successfully Added to Database");
}
In the end there is no comma and no issue
and in the database everything is fine
Now problem is that when i put a comma in the end there is a cell created in the database with whitespace
I know why this happening. The last key of the exploded array containing value is whitespace. But i want to omit or leave that empty key. How can i do that?
You should use array_filter() which will remove all empty keys from the array. So here is the code you should use:
$categories = array_filter(explode(",",$request->get('categories')));

Laravel: sorting collection by last name in single string

i'm trying to sort a collection, which consists of ids and full names, alphabetically by the last name.
the id comes from a parent class and the full name from the child.
I tried exploding the string and ordering according to the last name, but couldn't really get it to also reorder th IDs properly.
I tried both with sortBy while getting the collection and with usort after retrieving it
$testExaminers=TestExaminer::where('test_id',$request->testid)
->with('examiner')
->get()
->sortBy('examiner.name');
$result = array();
$num=0;
foreach($testExaminers as $testExaminer) {
$result[$num]['id'] = (int) $testExaminer->examiner_id;
$result[$num]['text'] = $testExaminer->examiner->name;
$num++;
}
echo json_encode(['examiners'=>$result]);
The code above works fine for sorting it by first name, but I need it to sort by last name.
user inputs test_id, which gives a list of "TestExaminers", each has a property "examiner_id" associated with a unique "examiner", which in turn has a name "firstname middlename lastname".
so it should look something like this
before sort
$result = [[1,'Alpha Z. Goodman'],[2,'Joe Bman'],[3,'ZZ Top'],[4,'Joe Aman']]
after sort
$result = [[4,'Joe Aman'],[2,'Joe Bman'],[1,'Alpha Z. Goodman'],[3,'ZZ Top']]
Thanks!
How about trying something like this?
$testExaminers = TestExaminer::where('test_id', $request->testid)
->with('examiner')
->get()
->map(function ($item, $key) {
$item->examiner->last_name = array_slice(explode(' ', $item->examiner->name), -1)[0];
return $item;
})
->sortBy('examiner.last_name');

create associative array while looping through collection in magneto 2

i have a collection object
$di=array();
$products= $this->customerFactory->create()->getCollection()->addAttributeToSelect('*')->addFieldToFilter('entity_id','22');
foreach ($products as $key => $value)
{ # code... }
I want to know how to loop through this collection and create associative array ..and if result has multiple rows how to loop through it.
As final result i should get the array as
{key=>value, key1=>value1}
First of all, getCollection() already returns an array of elements of the given collection, with all its attributes (addAttributeToSelect('*')), so you are already receiving an array of objects rather than a multi-dimensional array.
In the simplest of all cases and if you need a JSON array containing all the products with all attributes, it would be as simple as this:
$jsonArray= json_encode($products); // converts all elements into a JSON representation
If you would need an associative array of elements rather than an array of objects, typecast the objects:
$assocArray= array();
foreach ($products as $product) {
$assocArray[]= (array) $product; // type-casting to array
}
If you want to iterate over each property of each product (I wouldn't know why you would want that), here's that version:
$assocArray= array();
foreach ($products as $product) {
$rowArray= array();
foreach ($product as $key => $val) {
$rowArray[$key]= $val;
}
$assocArray[]= $rowArray;
}
Hope that gives you an idea of how collections can be used in Magento work.

Cast Laravel Collection into array

Here is my code$titles = DB::table('roles')->lists('title');
How Can I cast $titles from a Laravel 5 collection into an associative array?
Include the ID in the function, and call from the Model:
$titles = Role::lists('title', 'id')->toArray();
Or call directly as you are doing:
$titles = DB::table('roles')->lists('title', 'id');
In this case, in an select field for example, the id will be the option value.
A laravel collection has a toArray method that will return a numerically keyed array of the contents. (The indexes will be keyed exactly as they are in the collection. To reset them call values on the collection first.)
$titles = DB::table('roles')->lists('title');
$result = $titles->toArray();
For an associative array you will need to do this manually using something like this.
$titles = DB::table('roles')->lists('title', 'id');
$result = [];
foreach($titles as $title) {
// using an ID as the key and title as the value
$result[$title->id] = $title->title;
}

Append an array element to begining of a sorted Eloquent ::list array

I have a list of items in database table of a structure:
id, name.
I need to populate a select box with items sorted by their names along with "All" element with an id = 0 as the first one. What is wrong is that the element doesn't appear in a list box at all.
Controller method:
public function getItems(){
$items = Item::orderBy('name', 'ASC')->lists('name', 'id');
$items_all = array(0 => 'All');
array_merge($items_all, $items);
return View::make('items')->with('items', $items);
}
and a view:
{{ Form::select('item_id', $items, Input::Get('item_id'), array('class'=>'form-control')) }}
array_merge returns the new array, so you have to assign the return value to $items:
$items = array_merge($items_all, $items);
Or you can bring it down to this syntax if you want to:
$items = array_merge(['0' => 'All'], $items);
To preseve the order of your array items you can use this:
$items = $items_all + $items;
After updating
array_merge($items_all, $items)
to
$items = array_merge($items_all, $items)
all select box elements got displayed, including 'All', but array_merge renumbers elements, so I used:
$items = $items_all + $items;
as #lukasgeiter suggested at the same time, so I chose his answer as final.

Categories