Delete a duplicate string appearing in all array elements - php

In Laravel I can return data from Google analytics to get most visited page with this command:
$FilterData =$this->parseResults($data)->pluck('url');
It will be return this URLs:
[
"/products/r4-04",
"/products/r6-01",
"/products/cu3-20",
"/products/r4-51",
"/products/zp-1",
"/products/r5-31",
"/products/cu3-64",
"/products/cu6-01-1",
"/products/cu6-01-2",
"/products/r4-14",
"/products/t4-74",
"/products/cu-001",
"/products/cu5-18",
"/products/zp-8",
"/products/td6-01",
"/products/t4-14",
"/products/c6-01"
]
Now I want to remove all /products/ word from this and find the products by slug.

If you need just remove /products/ from every array value, you can use str_replace for this:
$FilterData =$this->parseResults($data)->pluck('url');
$FilterDataNew = str_replace("/products/","",$FilterData);
var_dump($FilterDataNew);

<?php
$products = [
"/products/r4-04",
"/products/r6-01",
"/products/cu3-20",
"/products/r4-51",
"/products/zp-1",
"/products/r5-31",
"/products/cu3-64",
"/products/cu6-01-1",
"/products/cu6-01-2",
"/products/r4-14",
"/products/t4-74",
"/products/cu-001",
"/products/cu5-18",
"/products/zp-8",
"/products/td6-01",
"/products/t4-14",
"/products/c6-01"
];
function replace($product) {
return str_replace('/products/', '', $product);
}
$products = array_map('replace', $products);

You can simple use str_replace to achieve the same.
Assuming your variable as $products
$array = str_replace('/products/', '', $products);
dd($array);

Related

Remove certain keys and values from associative array

I have a array that looks like this:
[['title'= >'my title','time'=>'14:00','date'=>'feb 2'],['title'= >'another','time'=>'14:00','date'=>'feb 2']]
Now I wish to remove all time and date keys from the arrays and also rename the title to text so it looks like this:
[['text'= >'my title'],['text'= >'another title']]
I have tried to use
$tags = array_map(function($tag) {
return array(
'text' => $tag['title'],
);
}, $tags);
But I cant get it to work
Laravel solution:
collect($array)->transform(function($i) { return ['text' => $i['title']]; })->toArray();
You can transform your collections,
$mycollection = $myModel->get();
return $mycollection->map(function($row){
return [
'text' => $row->title,
];
});
Or you can use Fractal: http://fractal.thephpleague.com/transformers/
$newTags = [];
foreach($tags as $tag) {
$newTags[] = [['text'] => $tag['title']];
}
$tags = $newTags;
This question isn't specific to Laravel, but since you mention it:
Use the collect() helper and it's methods for convenience. You'll want to look at pull, map, and maybe transform in particular.
If you don't use it then unset will delete the index you want from the array.
Alternatively, just create a new array:
$a = []
foreach($tags as $tag) {
$a[] = ['text' => $tag['title']];
}
edit: fix

Laravel Eloquent Pluck without losing the key

I have the following collection in Laravel:
["TheNumbers":[{"episodeID":16818,"episodeNumber":100,"created_at":null,"updated_at":null},{"episodeID":16818,"episodeNumber":210,"created_at":"2017-02-20 21:30:38","updated_at":"2017-02-20 21:30:38"}]
If I run the following code:
$TheEpisode->TheNumbers->pluck('episodeNumber');
I will get the following result:
[100,210]
I would like to keep the keys for each number, how can I achieve this?
EDIT: EXPECTED RESULT:
This is my expected result:
[{"episodeNumber":100},{"episodeNumber":210}]
PHILIS PETERS (improved)
TheEpisode->TheNumbers->reduce(function ($result, $episode) {
$episodeData = (collect())->put('episodeNumber', $episode['episodeNumber']);
$result[] = $episodeData;
return $result;
}));
Pluck() can take two params. The second of which is what the value can be keyed by.
You should be able to do:
$TheEpisode->TheNumbers->pluck('episodeNumber', 'episodeID');
Hope this helps!
Try something like this, it should work using map...
return $TheEpisode->TheNumbers->map(function ($episode) {
return ['episodeNumber' => $episode['episodeNumber']];
});
This can be simply achieved by passing a second argument to pluck. From the documentation:
You may also specify how you wish the resulting collection to be
keyed:
$plucked = $collection->pluck('name', 'product_id');
$plucked->all();
// ['prod-100' => 'Desk', 'prod-200' => 'Chair']
$collection->forget(['created_at', 'updated_at]);
This will simply left two first key-value pairs. Worth to keep in mind:
forget does not return a new modified collection; it modifies the collection it is called on.
Laravel docs
This should work properly:
$collection->only(['episodeID', 'episodeNumber']);
Try using
$TheEpisode->TheNumbers->lists('episodeNumber');
the key will remain.
Try using mapWithKeys like this:
$TheEpisode->TheNumbers->mapWithKeys(function ($theNumber) {
return ['episodeNumber' => $theNumber['episodeNumber']
});
I assume you want the result like this:
"TheNumbers":['episodeNumber':100,'episodeNumber':210]
For sake of updated Laravel, I tried all and I found
return Model::get(['name','id'])
will give reduced results with key => value.

Adding items to a php array without replacing the previous items

Am building a shopping cart and would like to append new items to a wishlist by adding them to a session but they shouldnt replace the existing items
This is what i have tried but returns an error of
[] operator not supported for strings
This is the code:
public function addItem($value, (int)$id){
if(isset($_SESSION[$value])){
$_SESSION[$value][] = array();
array_push($_SESSION[$value],array(
'id'=>$id
));
return true;
}
}
The values of $value is a string
I have also followed on This yii link and also on This link but still am getting the same error
By doing it this way
public function addItem($value, $id){
if(isset($_SESSION[$value])){
$_SESSION[$value] = array();
array_push($_SESSION[$value],array(
'id'=>$id
));
return true;
}
}
Adds the items but replaces whatever i had previously
WHAT DO I NEED TO CHANGE FOR IT TO WORK
You get this error when attempting to use the short array push syntax on a string. demo here.
$_SESSION[$value] is a string. so you cannot use something like $_SESSION[$value][]= 's'
So when the first time you use the $_SESSION[$value], make it an array. Not a string. Then you can use as $_SESSION[$value][]= 's';

Laravel Store Array in Session

I have been having trouble storing an array in session. I am making a shopping cart and it doesn't seem to work.
public function __construct(){
$product = array(1,2,3,4);
Session::push('cart', $product);
}
and then retrieve it in the view like this.
{{Session::get('cart')}}
However I keep getting an error like this.
htmlentities() expects parameter 1 to be string, array given
Any clues and advice on how to create a shopping cart that stores an array of items.
If you need to use the array from session as a string, you need to use Collection like this:
$product = collect([1,2,3,4]);
Session::push('cart', $product);
This will make it work when you will be using {{Session::get('cart');}} in your htmls. Be aware of Session::push because it will append always the new products in sessions. You should be using Session::put to be sure the products will be always updating.
You're storing an array in the session, and since {{ }} expects a string, you can't use {{Session::get('cart')}} to display the value.
The {{ $var }} is the same as writing echo htmlentities($var) (a very simple example).
Instead, you could do something like:
#foreach (Session::get('cart') as $product_id)
{{$product_id}}
#endforeach
If you use 'push', when initially creating the array in the session, then the array will look like this:
[
0 => [1,2,3,4]
]
Instead you should use 'put':
$products = [1,2,3,4];
$request->session()->put('cart', $products);
Any subsequent values should be pushed onto the session array:
$request->session()->push('cart', 5);
You can use .:
$product = array(1,2,3,4);
Session::put('cart.product',$product);
You can declare an array in session like
$cart = session('data', []);
$cart[] = $product;
session([ 'data' => $cart]);
return session('data', []);
you can also do it like that:
$data = collect($Array);
Session()->put('data', $data);
return view('pagename');

PHP return nothing if array_column fields are blank

The below code takes an array, $array, and an array key, $item and implodes by adding a comma to each item. How can I alter it so that if the value of the item inside the array is null, then the implode will not add a blank comma.
public static function implode($array, $item)
{
return implode(',', array_column($array, $item));
}
For example:
$array = [
['eri_number' => ''],
['eri_number' => '222']
['eri_number' => '']
];
$item = 'eri_number';
$myClass->implode($array, $item);
The above code will output;
,222,
I just want it to output 222 without the other blank values.
Can anyone help?
You could filter out the empties using array_filter():
return implode(',', array_filter(array_column($array, $item)));
Note that this will also filter out 0, string 0, false and null.
Apply array_filter to the array before imploding.
public static function implode($array, $item)
{
return implode(',', array_filer(array_column($array, $item)));
}
You can add a callback function to define what you want to filter out, but since the empty string is falsey, it should work for you right out of the box.

Categories