Laravel make array and use strtolower - php

I have data like this:
array:1 [
0 => "No Brand,ddfg"
]
First of all this data is wrong, what I want is to have something like this:
array:2 [
0 => "No Brand"
1 => "ddfg"
]
So now its really an array :)
Then I need my array data transform to lower case like:
array:2 [
0 => "no brand"
1 => "ddfg"
]
Code
$sibarBrandsArray = SidebarManager::first()->pluck('brands')->toArray();
This return data like:
array:1 [
0 => "No Brand,ddfg"
]
And this is how my data looks like in database:
Any idea?

Solved
// get my table row
$sibarBrandsArray = SidebarManager::first();
// get my row column
$getBrandColumn = $sibarBrandsArray->brands;
// separate data in that column with comma
$separateBrands = explode(',', $getBrandColumn);
// lowercase each separated data
$brandsArray = array_map('strtolower', $separateBrands);
// dump the result
dd($brandsArray);
Result
array:2 [
0 => "no brand"
1 => "ddfg"
]

Laravel has a very efficient and easy way to work with arrays. It's called a collection. Click here to learn more. Don't convert your response to the array, use collection directly.
$sibarBrandsCollection = SidebarManager::first()->pluck('brands');
Laravel eloquent by default gives you collection instance when you get a response. so pluck in above call is nothing but calling pluck on collection instance. We can chain method to the collection and do manipulation as needed.
$sibarBrandsCollection = $sibarBrandsCollection->map(function ($name) {
return strtolower($name);
});
Above code will automatically convert all of your values to lowercase. Similarly, you can explode the value to get your intended result. At last, if you have to send data as array to the browser just add toArray() method at the end of your collection.
I would not use core PHP array function unless needed, Laravel collection is great way to work with arrays.

$yourArray = array_map('strtolower', $yourArray);
$yourArray = array_map('nestedLowercase', $yourArray);
function nestedLowercase($value) {
if (is_array($value)) {
return array_map('nestedLowercase', $value);
}
return strtolower($value);
}
or you can use:
$query->whereRaw('LOWER(`newsTitle`) LIKE ? ',[trim(strtolower($newsTitle)).'%']);

Related

How to customize the implode function structure in resource in laravel

In my resource I've got an object like below:
return [
'something' => $this->somerelationship->implode('name',',')
];
Now it returns this result for me:
{
something [
"items,items,items"
]
}
But I want my implode to return a useable array in javascript not just making it 1 index of the array rather than that put each item in 1 slot of array-like below:
{
something
[
{items},{items},{items}"
]
}
How can I achieve that now ?
Instead of ->implode() (which takes an array and turn it into a string), try and do:
'something' => $this->somerelantionship->pluck('name')->all(),
The method pluck() returns an array with all the values from a specific key, which seems to be what you want.
You can return
json_encode($this->somerelationship->pluck('name')->toArray());
Then in your javascripts just JSON.parse() it or put it in a variable in blade:
var items = {!! json_decode($variable) !!}

How to add to an decoded Json Array from the Database specific selected Values

I am working on a movie WebApp. The User selects Movies and it gets added to the database. the column movie_list is a JSON because
I want that every time a User add a movie it gets added to the Array and if its already in it I want that it doesn't get added to the array
The problem is instead of adding it to the existing array it will sometime overwrite the Array, just add a nested Array or just create a custom key (0,1,2,3).
I tried to function like
array_merge and array_add
// It does overwrite it
array['checkedMovie'] = 3
Also thought about for each, but sadly dont know how to realize it.
My Brain is squeezed up.
public function update(Request $request, TrackMovie $trackMovie)
{
$currentCheckedMoviesArray = DB::table('track_movies')->where('user_id', $trackMovie->user_id)->get('checkedMovie');
$currentCheckedMoviesArray = json_decode($currentCheckedMoviesArray, true)[0];
$newarraychecked=array_add($currentCheckedMoviesArray,$currentCheckedMoviesArray['checkedMovie'], $trackMovie->checkedMovie);
return dd($newarraychecked);
$current_length = DB::table('track_movies')->where('user_id', $trackMovie>user_id)->value('lengthOfMovie');
DB::table('track_movies')->where('user_id', $trackMovie->user_id)->update([
'lengthOfMovie' => $current_length + $trackMovie->lengthOfMovie,
'checkedMovie' => $newarraychecked;
]);
return dd(TrackMovie::all());
}
To make it a bit clearly I edited this because I think its because of my formatting.
$currentCheckedMoviesArray = json_decode($currentCheckedMoviesArray, true)[0];
// DD Result
array:1 [▼
"checkedMovie" => "["1", "2"]"
]
$trackMovie->checkedMovie
//DD Result
array:2 [▼
0 => "2"
1 => "4"
]
$newarraychecked=Arr::collapse($currentCheckedMoviesArray, $trackMovie->checkedMovie);
//DD Result
[]
Actual Result:
This is the result what I get on the above code
array:1 [▼
"checkedMovie" => "["1", "2"]"
]
There some more because I tested many things
array:1 [▼
"checkedMovie" => "["1", "2"]"
1 => "2"
2 => "4"
]
Expected Result:
The User is checking some movies.
// He already has some movies
checkedMovie = ["1","2","3"]
Now the Application Checks if it already existed the movie in the Database.
If it does not contain in the database I want to add it. User selects Movie ID (5,6)
checkedMovie = ["1","2","3","5","6"]
After that, it will overwrite the Database column value
If I have forgotten something to add up to the question, please comment it so I can edit the question!
Try with the following:
$checkedMovie=array(1,2,3);
$selectedMovie=array(3,4,5,6);
$checkedMovie=array_unique(array_merge($checkedMovie,$selectedMovie));
You can just push the new values to the array and then use array_unique to filter out the duplicates
Example:
public function update(Request $request, TrackMovie $trackMovie)
{
//Get Current Array from DB
$currentCheckedMoviesArray = DB::table('track_movies')->where('user_id', $trackMovie->user_id)->get('checkedMovie');
$currentCheckedMoviesArray = json_decode($currentCheckedMoviesArray, true)[0];
//Decode JSON array
$currentCheckedMoviesArray['checkedMovie'] = json_decode($currentCheckedMoviesArray['checkedMovie'])
//Push the new Movie to the array
$currentCheckedMoviesArray['checkedMovie'][] = $trackMovie->checkedMovie;
//Remove duplicates from the array
$newarraychecked = array_unique($currentCheckedMoviesArray['checkedMovie']);
....
}

How to search for a value in array of objects and get it in Laravel?

How to search an array of objects and get a specific value if exists, and if not, take something else in Laravel 5.8?
Collection{
#items: array:3[
0 = Object{
attributes[
"id" => 1
"name" => 'google'
"url" => 'https://google.com/'
]
}
1 = Object
2 = Object
]
}
So out of this how to check if in this array there is an attribute url that has google.com in it? If something like this does not exists than get something else?
Is it possible to do this without looping?
Assuming the collection variable is $sites, you should be able to use the ->contains() closure to check if any of the $sites contains the google url:
$hasGoogle = $sites->contains(function ($site, $key) {
return $site->url == 'https://google.com';
});
if ($hasGoogle) {
// do something
} else {
// do something else
}
A boolean is returned from the ->contains() method.

Count Array values php

I am using laravel, I am getting this error when trying to count the valuse of this array.
Error:array_count_values(): Can only count STRING and INTEGER values!
the function:
public function test()
{
$test = \DB::table('surveys')->where('company_id', '=', 1)->select('rd1')->get()->toArray();;
$c = array_count_values($test);
$val = array_search(max($c), $c);
return view ('companies.test', compact('val'));
}
here is a var_dump of $test:
array:4 [▼
0 => {#204 ▼
+"rd1": "option1"
}
1 => {#206 ▼
+"rd1": "option1"
}
2 => {#207 ▼
+"rd1": "option1"
}
3 => {#208 ▼
+"rd1": "option1"
}
]
Your array is 2d which array_count_values doesn't like. You can either perform a loop and count the values yourself, or use something like array_column to get an array of the value from just the one column. Example:
array_count_values(array_column($test, $columnName))
array_column will get an array of values from just the one column you specify, which in your case is a string and that returned array can be passed to array_count_values to get the result you want.
Of course though, as someone else commented, this grouping and counting can be done by the database much more efficiently (you would be passing back less data and the database can be optimized to return queries like this with indexes). Here is another question that covers this.
You could then turn that back into a similar array with just array_column like:
\DB::table('surveys')
->where('company_id', '=', 1)
->select('rd1', \DB::raw('count(*) as total')
->groupBy('rd1')
->get()
->toArray();;
array_column($test, 'total', 'rd1');
The built-in function array_count_values() can't calculate the
frequency if the elements are not strings or numbers. You can, however,
easily perform a loop to do so:
foreach ($array as $e)
$frequency[$e] =+ 1;
This would basically do the same as the built-in. Note that the elements
are used as keys for the final frequency array (and you can imagina that
if $e is not a valid key (string or number) it will fail). In your
case, you need to use as key a property of your element. For example, if
it is another array:
foreach ($test as $e)
$frequency[$e['survey_name']] += 1;
Or properties/methods of an object:
foreach ($test as $e)
$frequency[$e->myColumn()] += 1;

get first element of an array

Lets assume, the return value of an search-fuction is something like this
// If only one record is found
$value = [
'records' => [
'record' => ['some', 'Important', 'Information']
]
]
// If multiple records are found
$value = [
'records' => [
'record' => [
0 => ['some', 'important', 'information'],
1 => ['some', 'information', 'I dont care']
]
]
]
what woul'd be the best way to get the important information (in case of multiple records, it is always the first one)?
Should I check something like
if (array_values($value['record']['records'])[0] == 0){//do something};
But I guess, there is a way more elegant solution.
Edit:
And btw, this is not realy a duplicate of the refered question which only covers the multiple records.
If you want the first element of an array, you should use reset. This function sets the pointer to the first element and returns it.
$firstValue = reset($value['record']['records']);
Edit.. after reading your question again, it seems, you dont want the first element.
You rather want this
if (isset($value['record']['records'][0]) && is_array($value['record']['records'][0])) {
// multiple return values
} else {
// single return value
}
Doing this is kind of error proun and i wouldn't suggest that one function returns different kinds of array structures.
check like this..
if(is_array($value['records']['record'][0])) {
// multiple records
} else {
// single record
}

Categories