How to array merge in laravel - php

I have a problem here, I want to combine 2 arrays into 1, I've tried using array_merge from php, and merge () from laravel but nothing works
//$plucked is EAV database
$vendor = Vendor::find($id)->toArray();
$vendor_detail = Vendor_detail::where('vendor_id',$id)->get();
$plucked = $vendor_detail->pluck('vendor_name','vendor_value');
$merged = array_merge($plucked, $vendor);
// $merged = $vendor->merge($plucked)->all();
dd($merged);
I think because the array is different, there array $plucked
#items: array:10 [▼
"user_email" => "cobaupdatelagi#gmail.com"
]
and there my array in $vendor
array:15 [▼
"vendor_id" => 39
"province" => "ACEH"
]
the output that I want
$somearray =[
"vendor_id" => 39
"province" => "ACEH"
"user_email" => "cobaupdatelagi#gmail.com"
]

Your $vendor is one associative array while $plucked is an array of arrays. Even if it has only one item it will be of index zero so you need to loop through $plucked and merge for each one.
$vendor = Vendor::find($id)->toArray();
$vendor_detail = Vendor_detail::where('vendor_id',$id)->get();
$plucked = $vendor_detail->pluck('vendor_name','vendor_value');
$merged = [];
foreach($plucked as $p){
$merged[] = array_merge($p, $vendor);
}
dd($merged);

$vendor = Vendor::find($id);
$vendor_detail = Vendor_detail::select('vendor_id','province')->where('vendor_id',$id)->get()->toArray();
$data= array_merge($vendor,$vendor_detail);

I think you should use database join to get faster results.
$vendor = Vendor::join('vendor_details', 'vendors.id', '=', 'vendor_details.vendor_id')
->select('vendors.*', 'vendor_name','vendor_value')
->where('id', $id)
->first();
if ($vendor) {
$vendor = $vendor->toArray();
}

$vendor_detail = Vendor_detail::where('vendor_id',$id)->get(); will give you a collection
as well as $plucked = $vendor_detail->pluck('vendor_name','vendor_value'); will give you a collection, so, either you can use collection merge or you may like to loop through one and add merge another as other answer is doing, but these are not array, you are getting collections.

Related

laravel Insert two array into the database

Hey guys I have to Arrays named $keys and $values Like this
keys
array:2 [▼
0 => "1"
1 => "2"
]
values
array:2 [▼
0 => "US"
1 => "Canada"
]
And I want to insert them to the database with my controller :
$keys = $request->key;
$values = $request->value;
$datas = new Collection();
$datas->key_id = $keys;
$datas->value = $values;
$datas->product_id = $product_id;
ProductSearchValuesModel::create($datas);
But this way is not working
What is wrong with my code?
It's better to change those array to jSon format. Please! check this code.
$datas = new Collection();
$datas->key_id = json_encode($keys);
$datas->value = json_encode($values);
$datas->product_id = $product_id;
ProductSearchValuesModel::create($datas);
You'll have to use json_decode($array, 1) whenever you want to pull from database and use them. Also please check field length of that table ProductSearchValues to make sure it can hold that data.
Thanks

elements in array is not working with in_array

number 3 should be in array $songsid but when i used in_array method output was null
nuder my function is dd($songsid)
public function index()
{
$songs = Song::latest()->paginate(20);
$songid = Collection::select("song_id")->where("user_id", "=", auth::user()->id)->get();
$songsid = $songid->toArray();
// dd($songsid);
if(in_array(3, $songsid))
{
dd("yes");
}
else
{
dd("no");
}
}
output of $songsid array dd($songsid)
array:2 [▼
0 => array:1 [▼
"song_id" => 3
]
1 => array:1 [▼
"song_id" => 2
]
]
$songsid is not an array of scalar values, but an array of arrays.
You could use array_column() to extract IDs from the array,
in_array(3, array_column($songsid, 'song_id')
Unless you really need to convert to array, you could use collection methods to check that out.
$songid = Collection::select("song_id")->where("user_id", "=", auth::user()->id)->get();
if ($songId->contains('song_id', 3)) ...
In your in_array method, you need an indexed array, ex : $songsid = [3,2]; You can use pluck method :
$songsid = $songid->pluck('id')->toArray();
if(in_array(3, $songsid))
{
dd("yes");
} else {
dd("no");
}
in_array() searches in the array values, that is not nesting.
You may want to use array_culumn() like
in_array(3, array_column($songsid, 'song_id')
or search for ['song_id' => 3] like
in_array(3, array_column($songsid, ['song_id' => 3])

Remove duplicate attributes from a collection Laravel

For some strange reason, my collection (returned from query) is showing duplicate attribute 4 times exactly. Is there a way to remove duplicate or repeated attributes.
#attributes: array:2 [▼
"name" => "Ram Inden"
"features" => "2,2,2,2,3,3,3,3,4,4,4,4"
In this collection, the features attributes only should have 2,3,4 but it's repeated four times, and I don't know why. In my database it's only 2,3,4.
Another thing, this thing only appears at a Live server, my localhost works fine.
Any help would be really appreciated
Use php explode,array_uniqe,join function
$collection = collect([
"name" => "Ram Inden",
"features" => "2,2,2,2,3,3,3,3,4,4,4,4"
]);
$unique = join(',', array_unique(explode(',', $collection['features'])));
$collection['features'] = $unique;
return $collection;
Starting from the collection you could eliminate the duplicates in the following way:
$collection = collect([
"name" => "Ram Inden",
"features" => "2,2,2,2,3,3,3,3,4,4,4,4"
]);
$str = $collection['features'];
$collection->prepend(implode(',',array_unique(explode(',', $str))) ,'features');
return $collection;

Split multidimensional array into arrays

So I have a result from a form post that looks like this:
$data = [
'id_1' => [
'0' => 1,
'1' => 2
],
'id_2' => [
'0' => 3,
'1' => 4
],
'id_3' => [
'0' => 5,
'1' => 6
]
];
What I want to achieve is to split this array into two different arrays like this:
$item_1 = [
'id_1' => 1,
'id_2' => 3,
'id_3' => 5
]
$item_2 = [
'id_1' => 2,
'id_2' => 4,
'id_3' => 6
]
I've tried using all of the proper array methods such as array_chunk, array_merge with loops but I can't seem to get my mind wrapped around how to achieve this. I've seen a lot of similar posts where the first keys doesn't have names like my array does (id_1, id_2, id_3). But in my case the names of the keys are crucial since they need to be set as the names of the keys in the individual arrays.
Much shorter than this will be hard to find:
$item1 = array_map('reset', $data);
$item2 = array_map('end', $data);
Explanation
array_map expects a callback function as its first argument. In the first line this is reset, so reset will be called on every element of $data, effectively taking the first element values of the sub arrays. array_map combines these results in a new array, keeping the original keys.
The second line does the same, but with the function end, which effectively grabs the last element's values of the sub-arrays.
The fact that both reset and end move the internal array pointer, is of no concern. The only thing that matters here is that they also return the value of the element where they put that pointer to.
Solution without loop and just for fun:
$result = [[], []];
$keys = array_keys($data);
array_map(function($item) use(&$result, &$keys) {
$key = array_shift($keys);
$result[0][$key] = $item[0];
$result[1][$key] = $item[1];
}, $data);
Just a normal foreach loop will do.
$item_1 = [];
$item_2 = [];
foreach ($data as $k => $v){
$item_1[$k] = $v[0];
$item_2[$k] = $v[1];
}
Hope this helps.

PHP array loop and format

I am very new to PHP, learning fast but not fast enough! I am also learning Laravel 5.1.
I am trying to build a HTML select list array from an Eloquent query output, in the correct format for form builder (Form::select).
I have the following call to Eloquent to pull the data:
// Get list of States for address select
$states = State::all()->toArray();
It returns the following array:
array:8 [▼
0 => array:2 [▼
"id" => "1"
"state" => "ACT"
]
1 => array:2 [▼
"id" => "2"
"state" => "NSW"
]
...
];
I want to loop through it and generate the following output:
array = [
'' => 'State', <-- This is the default for the select list
'1' => 'ACT',
'2' => 'NSW',
...
];
I am using Laravel 5.1, so I am using the included array_add() function in my helper.
I call my function like this:
$states = create_select_list($states, 'State');
I next want to format the output so it is ready for the Form::select statement. I have tried the code below (as the final try from a few iterations!) but unsuccessfully.
function create_select_list($data, $default)
{
// Declare array and set up default select item
$container = ['' => $default];
// Loop through data entries and build select list array
foreach($data as list($entry, list($key, $value))) {
$container = array_add($container, $key, $value);
}
// Return the select list array
return $container;
}
All help or suggestions are appreciated!
This answer is not about loop fix. I think previous comment should help you.
Just another idea. You can try use array_map instead foreach for this case.
For example:
$states = ['' => 'State'];
array_map(function($item) use (&$states) {
$states[$item['id']] = $item['state'];
}, State::all()->toArray());
Loop like below:
foreach($data as $key => $keyArr ) {
$container = array_add($container, $keyArr['id'], $keyArr['state']);
}
You don't need to use list() in your foreach loop, instead try:
foreach($data as $key => $value) {
$container = array_add($container, $key, $value);
}
The PHP documentation gives a good overview of what list() actually does.

Categories