I want to check if all the values of my input, an array, are in another array. For example:
$my_arr = ['item1', 'item2', 'item3', 'item4'];
Validator::make($request, [
'item' => [ /* what do i put here??? */ ],
]);
I don't think the rule in works, because that expects a single value as input, not an array. in_array doesn't work either. I've tried creating a custom rule or closure, but neither of those allow me to pass in a parameter (the array I want to check against). Especially since I want this same functionality for multiple arrays, for different inputs, it would be nice to have a generic rule that works for any array I give it.
If that's not possible, I suppose I need to create a rule for each specific array and use !array_diff($search_this, $all) as this answer says. Is there an alternative to this?
True that in doesn't accept an array but a string. So you can just convert the array into a string.
$my_arr = ['item1', 'item2', 'item3', 'item4'];
Validator::make($request, [
'item' => [ 'in:' . implode(',', $my_arr) ],
]);
implode
Another better solution might be to use Illuminate\Validation\Rule's in method that accepts an array:
'item' => [ Rule::in($my_arr) ],
Laravel Validation - Rule::in
Related
Let's say for example you have a constant multi-dimensional array with multiple keys (and values), but you want to filter out specific keys with it's values. See a example array below:
const defaultInvestmentFields = [
[
'type' => 'system',
'investment_name' => 'Ballast'
],
[
'type' => 'system',
'investment_name' => 'Inverters'
],
[
'type' => 'system',
'investment_name' => 'Extra garantie inverters'
]
];
The output I want is an array with only the values of investment_name. Like ['Ballast', 'Inverters', 'Extra garantie inverters'].
Additionally to #Levi's answer, you can use an array helper to avoid having to transform the array into a collection and back: Arr::pluck()
Arr::pluck(Project::defaultInvestmentFields, 'investment_name');
A quick and neat solution would be to use the collect wrapper function which is provided by Laravel. After that we can use the pluck function in order to specify which values by their key(s) we want to get. For example:
collect(Project::defaultInvestmentFields)->pluck('investment_name');
Now we have a Collection of the following values: Ballast, Inverters and Extra garantie inverters.
In order to use it as an array, simply call toArray() on it.
I have to pass a query parameters with different values but absolutely equal keys. I found this \GuzzleHttp\Psr7\build_query(); But it returns only last value. For instance:
$array = [
'test' => '1',
'test' => '2'
]
\GuzzleHttp\Psr7\build_query($array);
//OR
http_query_builder($array);
It returns every time string with the last item.
Does it possible to do that with PHP? Because the side which will take these parameters just can not do anything in their side so I have to pass parameters with the equal keys.
The problem was not with the specific method used, but with how you filled your array to begin with:
$array = [
'test' => '1',
'test' => '2'
]
You can not use the same array key twice; your array only contains one element now, because the second one has overwritten the existing first one under that same key.
Make the test element itself an array, that contains your two values:
$array = [
'test' => ['1', '2']
];
I'm trying to construct an array where there only strings and the array would look like this
key->key->value
To explain it I attached two screenshots below.
I start with this:
After my code below I'm 90% there, yet there is an array in value on the third level instead of simple value.
Here is some code:
$theme = ThemeHandler::with('sections.settings')->find($activeTheme);
$themeSettings = $theme->sections;
$themeSettings = collect($themeSettings->toArray());
// dd($themeSettings);
$themeSections = [];
foreach ($themeSettings as $key => $value) {
$settings = collect($value['settings']);
$settings = $settings->mapToGroups(function ($item) {
return [$item['key'] => $item['value']];
});
$themeSections[$value['key']] = $settings->toArray();
}
dd($themeSections);
I would like to end up with this structure
key->key->value
and not
key->key->single_element_array->value
I'm not sure how I end up with an array at the bottom level when I do this
return [$item['key'] => $item['value']];
inside the mapToGroups, which is a function found here: https://laravel.com/docs/5.8/collections#method-maptogroups
Maybe I misunderstand how mapToGroups work. Anybody has an idea how to get key->key->value structure output?
Use mapWithKeys() instead of mapToGroups().
You're getting an array instead of the simple value you expect because the value is a group, albeit a group with only one member.
mapToGroups() groups all the values with the same key, but mapWithKeys() will assign a single value to each key.
You can see in the examples in the collection documentation, mapToGroups() produces a result like this:
[
'Sales' => ['John Doe', 'Jane Doe'],
'Marketing' => ['Johnny Doe'],
]
And mapWithKeys() result is like this:
[
'john#example.com' => 'John',
'jane#example.com' => 'Jane',
]
Is possible use something like array_pluck($array, 'users.*.id')?
Imagine that I have:
$array = [
'users' => [
[ 'id' => 1 ],
[ 'id' => 2 ],
[ 'id' => 3 ],
]
];
And I want get [1, 2, 3].
I tried something like: users.*.id, users.id and users..id, but nothing worked.
From Laravel 5.7, you may use the Arr::pluck() helper.
use Illuminate\Support\Arr;
Arr::pluck($array['users'], 'id')
Use array_pluck($array['users'], 'id')
The function only supports a single dimensional array. It will search for keys in the array which match the second parameter; which in your case is 'id'. You'll note that the array you're searching in your examples only has a key named users and none with the name id.
Using $array['users'] means pluck looks through that array and subsequently finds keys named id on each element.
You can use Laravel collections to achieve something like this.
$data = collect($array['users']);
$ids = $data->pluck('id');
return $ids;
you should use https://laravel.com/docs/5.7/helpers#method-array-pluck.
Don't recreate helpers that already exist ;)
I would like to make associative array using foreach to use in Yii 2 dropdownlist.
My goal is to make array like following using foreach-
$array= [
['id' => '123', 'name' => 'abc'],
['id' => '124', 'name' => 'def'],
];
And then I want to use them using Yii 2 ArrayHelper::map().
$result = ArrayHelper::map($array, 'id', 'name');
How do I make the array using foreach?
Yii way to build items for drop-down list is exactly as you described, using ArrayHelper::map():
$items = ArrayHelper::map($array, 'id', 'name');
You don't need to use foreach here, just pass results of ActiveQuery as array:
$array = YourModel::find()->all();
Update:
Thanks. But here, I am actually calculating custom value for 'name'
and for that reason I want to use foreach to generate the array after
the calculation
You definetely need to add this information to the question, but anyway, you can use the ArrayHelper for that too. Take a look at toArray method. It can be used for both object / array of objects. After processing with this method you can use map.
Official docs:
ArrayHelper::map()
ArrayHelper::toArray()