Convert multiple array into a string in laravel - php

$est_data = Establishments::where('status',0)->where('city','=',$data['location'])->get(array('id'));
return $est_data;
result:
[{"id":43},{"id":71},{"id":41},{"id":39}]
This is my above laravel condition and result, i want the result to be like 43,71,41,39.
Can anyone please help me, how can be this done using php. i tried with implode() function, but getting error, please help...thank you

Laravel pluck method will select required fields only:
$est_data = Establishments::where('status',0)->where('city','=',$data['location'])->pluck('id');
return $est_data;
As commented by #apokryfos for your laravel version (4.2) lists method should be used, so it is:
$est_data = Establishments::where('status',0)->where('city','=',$data['location'])->lists('id');
return $est_data;

You can use the laravel array_flatten() array helper:
The array_flatten function flattens a multi-dimensional array into a
single level array:
$array = array('name' => 'Joe', 'languages' => array('PHP', 'Ruby'));
$array = array_flatten($array);
// array('Joe', 'PHP', 'Ruby');
In your case:
$est_data = Establishments::where('status',0)->where('city','=',$data['location'])->pluck('id');
return array_flatten($est_data);

$result = implode(',',$est_data[0]);
This will solve your problem. You should read about implode(convert to string) and explode (string to array). They are really useful php functions.
Reading your comment, your error is coming from the fact that you try to access $set_data and not $set_data[0] where you values are based on the output you provided us.

Use the php array_column function, specifying the id:
$est_data = Establishments::where('status',0)->where('city','=',$data['location'])->pluck('id');
return array_column("id", $est_data);

Related

How do I work with an array object in PHP?

I have a Laravel site I am modifying, but there are some parts of the PHP code I don't quite understand, which are "array objects" or "object arrays". You see, I don't even know what to call them and so can't find a tutorial or basic data on it. Below is the code that I am dealing with:
private function parseMetric($result, $view)
{
$data = collect([]);
$result->each(function($item) use ($data, $view) {
if (isset($item->metric->{$view})) {
$data->push((object)[
'label' => $item->metric->{$view},
'value' => $item->metric->count
]);
}
});
...
From what I can tell, this creates an object out of $result. If I json_encode this and echo it out I get this:
[{"label":"1k-25k","value":14229},
{"label":"1mm+","value":1281},
{"label":"25k-50k","value":398},
{"label":"50k-75k","value":493},
{"label":"75k-100k","value":3848},
{"label":"100k-150k","value":9921},
{"label":"150k-200k","value":4949},
{"label":"200k-250k","value":3883},
{"label":"250k-300k","value":2685},
{"label":"300k-350k","value":2744},
{"label":"350k-500k","value":4526},
{"label":"500k-1mm","value":8690}]
Now this is obviously an array of arrays... or is it? Is it an array of objects? Or is it an object containing arrays? But the most important question is, how do I access and move or change the individual objects/arrays in this object? For example, I want to take the second object/array, which is:
{"label":"1mm+","value":1281}
and move it to the end. How do I do that? How do I find it? I used the following piece of code to find it which is pretty clunky:
$pos = strpos(json_encode($result), '1mm+');
if($pos){
Log::debug('Enrich 73, I found it!!!!!!!!!!!!!!!!!!!!!!!!!!!');
}
And once I find it, how do I move that array/object to the end of the whole object?
And finally, where can I find some kind of tutorial, or documentation, that describes this construct and how to work with it?
There is no need to json_encode the data. Since the data is an instance of Laravel Collection, you can manipulate it like so
$item = $data->firstWhere('label', '1mm+'); // get the item
$data = $data->filter(fn($value, $key) => $value->label !== '1mm+') // remove $item from $data
->push($item); // move $item to the end of data
Acording to Laravel documnentation for Collections, you can try something like this :
To find index of element with name = "1mm+" :
$index = $datas->search(function ($item, $key) {
return $item['name'] == "1mm+";
});
to get an element at a given index :
$element = $datas->get($index);
to Move element at index 3 to the end :
$index = 3
$elementToMove = $data->splice($index, 1);
$datas->push($elementToMove);
Here is a link to the document used : https://laravel.com/docs/8.x/collections

Get all values for specific key in an array of associative array [duplicate]

This question already has answers here:
Is there a function to extract a 'column' from an array in PHP?
(15 answers)
Closed 10 months ago.
Let's assume I have the following multidimensional array (retrieved from MySQL or a service):
array(
array(
[id] => xxx,
[name] => blah
),
array(
[id] => yyy,
[name] => blahblah
),
array(
[id] => zzz,
[name] => blahblahblah
),
)
Can we get an array of ids in one "built-in" php function call? or one line of code?
I am aware of the traditional looping and getting the value but I don't need this:
foreach($users as $user) {
$ids[] = $user['id'];
}
print_r($ids);
Maybe some array_map() and call_user_func_array() can do the magic.
Since PHP 5.5, you can use array_column:
$ids = array_column($users, 'id');
This is the preferred option on any modern project. However, if you must support PHP<5.5, the following alternatives exist:
Since PHP 5.3, you can use array_map with an anonymous function, like this:
$ids = array_map(function ($ar) {return $ar['id'];}, $users);
Before (Technically PHP 4.0.6+), you must create an anonymous function with create_function instead:
$ids = array_map(create_function('$ar', 'return $ar["id"];'), $users);
PHP 5.5+
Starting PHP5.5+ you have array_column() available to you, which makes all of the below obsolete.
PHP 5.3+
$ids = array_map(function ($ar) {return $ar['id'];}, $users);
Solution by #phihag will work flawlessly in PHP starting from PHP 5.3.0, if you
need support before that, you will need to copy that wp_list_pluck.
PHP < 5.3
Wordpress 3.1+
In Wordpress there is a function called wp_list_pluck
If you're using Wordpress that solves your problem.
PHP < 5.3
If you're not using Wordpress, since the code is open source you can copy paste the code in your project (and rename the function to something you prefer, like array_pick). View source here
If id is the first key in the array, this'll do:
$ids = array_map('current', $users);
You should not necessarily rely on this though. :)
You can also use array_reduce() if you prefer a more functional approach
For instance:
$userNames = array_reduce($users, function ($carry, $user) {
array_push($carry, $user['name']);
return $carry;
}, []);
Or if you like to be fancy,
$userNames = [];
array_map(function ($user) use (&$userNames){
$userNames[]=$user['name'];
}, $users);
This and all the methods above do loop behind the scenes though ;)

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.

Why am I getting a dictionary as a result when the result should be an array?

I am using Doctrine in my PHP app to return a result set using the following code
$dm = $this->get('doctrine.odm.mongodb.document_manager');
$query = $dm->createQueryBuilder('SomeBundle:Listing')
->select('title')
->field('userId')->equals(1);
$listings = $query->getQuery()->execute();
$listings_array = $listings->toArray(); <--- WHY NOT RETURNING AN ARRAY?????
$data = array('success'=>true,'listings' => $listings_array, 'displaymessage' => $classifieds->count(). " Listings Found");
What gets out out is the following:
{"success":true,"listings":{"50831582253b4acf09000000":{"id":"50831582253b4acf09000000","title":"fddfds","assets":[],"discussions":[]}},"displaymessage":"1 Listings Found"}
I am wanting an array and not a dictionary.
Any help?
I havent messed with the ODM much but i suspect Doctrine always uses the key for the record as the key in the array when calling toArray on a collection, it makes it easier for most of the cases when you would want to do this, especially since there is no distinction in php between a dict/hash and an array.
Call array_values on it if you want a numerically indexed array.
$data = array(
'success'=>true,
'listings' => array_values($listings_array),
'displaymessage' => $classifieds->count(). " Listings Found"
);

How to get an array of specific "key" in multidimensional array without looping [duplicate]

This question already has answers here:
Is there a function to extract a 'column' from an array in PHP?
(15 answers)
Closed 10 months ago.
Let's assume I have the following multidimensional array (retrieved from MySQL or a service):
array(
array(
[id] => xxx,
[name] => blah
),
array(
[id] => yyy,
[name] => blahblah
),
array(
[id] => zzz,
[name] => blahblahblah
),
)
Can we get an array of ids in one "built-in" php function call? or one line of code?
I am aware of the traditional looping and getting the value but I don't need this:
foreach($users as $user) {
$ids[] = $user['id'];
}
print_r($ids);
Maybe some array_map() and call_user_func_array() can do the magic.
Since PHP 5.5, you can use array_column:
$ids = array_column($users, 'id');
This is the preferred option on any modern project. However, if you must support PHP<5.5, the following alternatives exist:
Since PHP 5.3, you can use array_map with an anonymous function, like this:
$ids = array_map(function ($ar) {return $ar['id'];}, $users);
Before (Technically PHP 4.0.6+), you must create an anonymous function with create_function instead:
$ids = array_map(create_function('$ar', 'return $ar["id"];'), $users);
PHP 5.5+
Starting PHP5.5+ you have array_column() available to you, which makes all of the below obsolete.
PHP 5.3+
$ids = array_map(function ($ar) {return $ar['id'];}, $users);
Solution by #phihag will work flawlessly in PHP starting from PHP 5.3.0, if you
need support before that, you will need to copy that wp_list_pluck.
PHP < 5.3
Wordpress 3.1+
In Wordpress there is a function called wp_list_pluck
If you're using Wordpress that solves your problem.
PHP < 5.3
If you're not using Wordpress, since the code is open source you can copy paste the code in your project (and rename the function to something you prefer, like array_pick). View source here
If id is the first key in the array, this'll do:
$ids = array_map('current', $users);
You should not necessarily rely on this though. :)
You can also use array_reduce() if you prefer a more functional approach
For instance:
$userNames = array_reduce($users, function ($carry, $user) {
array_push($carry, $user['name']);
return $carry;
}, []);
Or if you like to be fancy,
$userNames = [];
array_map(function ($user) use (&$userNames){
$userNames[]=$user['name'];
}, $users);
This and all the methods above do loop behind the scenes though ;)

Categories