This question already has answers here:
Is there a function to extract a 'column' from an array in PHP?
(15 answers)
Closed 1 year ago.
I am quite new no laravel. I know that it is a pretty basic question. But, I still can't figure it out. Heres my Array output and I want to get the value of name from within this array. This is the output I get in postman after I used print_r:
Array
(
[0] => Array
(
[name] => Test 2322
[id] => 4
)
)
if you want all of them
foreach ($datas as $datavals) {
echo $datavals['name'];
}
If you want 0 array name element value Just call following :
echo $memus[0]['name'];
In case this is a collection you can use the pluck method
$collection = collect([
['product_id' => 'prod-100', 'name' => 'Desk'],
['product_id' => 'prod-200', 'name' => 'Chair'],
]);
$plucked = $collection->pluck('name');
$plucked->all();
// ['Desk', 'Chair']
If in your case you do not have a collection you can create it with the collect method.
In your case:
$myarray = collect($initialArray); //You can ignore this if it is already an array
$nameArray = $myarray->pluck('name')->all();
foreach($nameArray as $name)
{
echo $name; //Test 2322
}
You can iterate the array with foreach on blade and get index="name" for each entry like this:
In View
#foreach($data as $d)
{{$d['name']}}
#endforeach
In Controller
foreach($data as $d){
// This is the value you want
$name = $d['name']
}
Simply write the array name with the indices and key which have to access.Suppose $a[] is array then $a[0]['name'] and the value at zero index of array will be retrieved or you can parse it in loop which will give the value of key ['name'] at every indices.
foreach($a as $item)
{
print_r($item['name']);
}
In newest version of laravel you can use the Arr::pluck() helper function to take an array of all names values.
In your case
Arr::pluck($array, 'name')
Will output
['Test 2322']
Related
This question already has answers here:
Is there a function to extract a 'column' from an array in PHP?
(15 answers)
Closed 9 months ago.
I have this array. I want to get the array values to a same array,how can I achieve that?
Array
(
[0] => Array
(
[referrer_id] => usr157
)
[1] => Array
(
[referrer_id] => usr42
)
)
I want this array to be
array("usr157", "usr42")
use array_walk_recursive to achieve the result as follows
<?php
$main = [];
$ref =
[
[
"referrer_id" => "usr157"
],
[
"referrer_id" => "usr42"
]
];
array_walk_recursive($ref, function ($item, $key) use(&$main) {
$main[] = $item;
} );
print_r($main);
You can check that out here
You can just access the array components like this:
// The next line just recreates your example array into a variable called $x:
$x = array(array('referrer_id' => 'usr157'), array('referrer_id' => 'usr42'));
$result = array($x[0]['referrer_id'], $x[1]['referrer_id']);
print_r($result); //print the result for correctness checking
$result will be the output array you wanted.
Using $x[0], you refer the first element of your input array (and hence, $x[1] the second one, ...). Adding ['referrer_id'] will access its referrer_id key. The surrounding array(...) puts the values into an own array.
You can "automate" the whole thing in case you have a bigger input array using a loop.
You may use array_column to achieve that
$flatten = array_column($array, 'referrer_id');
You can also use array_map and array_values together.
$array = [
[
"referrer_id" => "usr157"
],
[
"referrer_id" => "usr42"
]
];
$flatten = array_map(function($item) {
return array_values($item)[0];
}, $array);
var_dump($flatten);
Also you can use the one-liner if you're using latest version of php that support arrow function
$flatten = array_map(fn($item) => array_values($item)[0], $array);
Or without array_values, you may specify the key
$flatten = array_map(fn($item) => $item['referrer_id'], $array);
You can see the demo here
I have this array:
$datas = array(
array(
'id' => '1',
'country' => 'Canada',
'cities' => array(
array(
'city' => 'Montreal',
'lang' => 'french'
),
array(
'city' => 'Ottawa',
'lang' => 'english'
)
)
)
);
Question 1:
How can I get the the country name when I have the id ?
I tried: $datas['id'][1] => 'country'
Question 2:
How can I loop in the cities when I have the id ?
I tried:
foreach ($datas as $data => $info) {
foreach ($info['cities'] as $item) {
echo '<li>'.$item['city'].'</li>';
}
}
Thanks a lot.
You have the ID of the array you want analyse, but your array is structured as a map, meaning that there are no keys in the outer array. You will therefore have to iterate the array first to find the object you are looking for.
While the first approach would be to search for the object that has the ID you are looking for, i suggest you map your arrays with their IDs. To do that, you can use two PHP array functions: array_column and array_combine.
array_column can extract a specific field of each element in an array. Since you have multiple country objects, we want to extract the ID from it to later use it as a key.
array_combine takes two arrays with the same size to create a new associative array. The values of the first array will then be used as keys, while the ones of the second array will be used as values.
$mappedCountries = array_combine(array_column($datas, 'id'), $datas);
Assuming that the key 1 is stored in the variable $key = 1;, you can afterwards use $mappedCountries[$key]['country'] to get the name of the country and $mappedCountries[$key]['cities'] to get the cities, over which you can then iterate.
if there might be many arrays in $datas and you want to find one by id (or some other key) you can do something like this:
function search($datas, $key, $value) {
foreach($datas as $data) {
if ($data[$key] === $value) {
return $data;
}
}
So if you want to find where id = 1
$result = search($datas, 'id', '1');
and then you can get country echo $result['country'] or whatever you need.
I am struggling with what would appear to be a pretty straight forward task. I have looked at and tried all kinds of functions and suggestion on SO hoping that maybe there is something simple and functional out there. Nothing I tried gives me the logic to do the restructuring.
I have a long complex array. However very much simplified the logic problem I am trying to solve generically is as follows:
$cost_type = Array
(
0 => "ISP2",
1 => "ISP3",
2 => "ISP4"
);
$supplier_name = Array
(
0 => "NAME-A",
1 => "NAME-B",
2 => "NAME-C"
);
$propertyid = Array
(
0 => "property1",
1 => "property2",
2 => "property2"
);
and I need to convert it to the following set of arrays (noting the concatenation of the two arrays with a common property id.....
$property1
(
array['charges']
[0] =>IPS2
array ['names']
[0] =>NAME-A
)
$property2
(
array['charges']
[0] ->IPS3
[1] =>IPS4
array['names']
[0] =>NAME-B
[1] =>NAME-c
)
I have tried everything over the course of the last few hours and a simple solution totally evades me.
If you can join the three arrays as you say in comments above this code will generate the look you want.
I loop through the array with property and keep key as the key to find names and charges in the other subarrays.
$cost_type = Array
(
0 => "ISP2",
1 => "ISP3",
2 => "ISP4"
);
$supplier_name =Array
(
0 => "NAME-A",
1 => "NAME-B",
2 => "NAME-C"
);
$propertyid = Array
(
0 => "property1",
1 => "property2",
2 => "property2"
);
$arr[] = $cost_type;
$arr[] = $supplier_name;
$arr[] = $propertyid;
$result = array();
Foreach($arr[2] as $key => $prop){
$result[$prop]["charges"][] =$arr[0][$key];
$result[$prop]["names"][] = $arr[1][$key];
}
Var_dump($result);
https://3v4l.org/EilvE
The following code converts the original array in the expected result:
$res = array();
foreach($arr[2] as $k => $foo){ // foreach property
if(!isset($res[$foo])){ // add property if not yet in list
$res[$foo] = array(
'charges' => array($arr[0][$k]),
'names' => array($arr[1][$k])
);
}else{ // add new value to already existing property
$res[$foo]['charges'][] = $arr[0][$k];
$res[$foo]['names'][] = $arr[1][$k];
}
}
Check it out here: https://eval.in/904473
Of course, it assumes a bunch on things about the data, but it should work for any number of items.
And if you need the property in another variable, just access it with $res['name of it].
Run this code you will get smiler result as you want :
$twodimantion=array();
$properties=array('property1','property2','property3');
$charges=array('ISP2','ISP3','ISP4');
$names=array('NAME-A','NAME-B','NAME-C');
foreach ($properties as $key => $property) {
$twodimantion['charge'][$key]=$charges[$key];
$twodimantion['names'][$key]=$names[$key];
$twoarray[$property]=$twodimantion;
}
echo '<pre>';
print_r($twoarray);
echo '</pre>';
I can't say I completely follow what you are trying to do, but I think this may be part of the way there for you.
When trying to restructure data in PHP, it's often helpful to create a empty array (or other data structure) to store the new data in first. Then you find a way to loop over your initial data structure that allows you to insert items into your reformatted structure in the right sequence.
<?php
$properties = []; // Array to hold final result
// Loop over your initial inputs
foreach ($groupsOfValues as $groupName => $groupValues) {
$temp = []; // Array to hold each groupings reformatted data
// Loop over the items in one of the inputs
for ($i=0; $i<count($group) && $i<count($properties)+1; $i++) {
if (!is_array($temp[$groupName])) {
$temp[$groupName] = [];
}
$temp[$groupName][] = $group[$i];
}
$properties[] = $temp;
}
This question already has answers here:
Is there a function to extract a 'column' from an array in PHP?
(15 answers)
Closed 6 years ago.
I need to change this array:
$array = [
[0] => [
'id' => '100'
],
[1] => [
'id' => '200'
],
[2] => [
'id' => '300'
]
];
Into this:
$array2 = [100, 200, 300];
A long time ago I found a built-in PHP function which could do this for me. But i can't for the life of me remember which one it was. Of course I could do it manually, but it would be easier and more readable if I could use a builtin PHP function
Use array_column like this: array_column($array, 'id');
1st solution:
Use array_map() function with inline function:
$array2 = array_map(function($arrayElement){return $arrayElement['id'];}, $array);
2nd solution:
Use foreach loop:
function getValues($array, $index)
{
$result = array();
foreach($array as $element)
{
if(isset($element[$index])) //check if index exists
$result[] = $element[$index];
}
return $result;
}
$array2 = getValues($array, 'id');
This function has two parameters: array from which you gets values and index, for example 'id'.
Result of two methods is the same:
Array
(
[0] => 100
[1] => 200
[2] => 300
)
I have a weird phenomenon. I hope someone can explain to me what is happening there:
I want to create a filter. The origin is something like '-10' or '10-20' or '20+' (type string) and the result should be 'Under $10', ... as well as 'product_price < 10', ... for a sql command.
But storing the array back on the original string doesn't work. It just delivers '$Array' as result. Is it not possible to pass by reference and change the type?
Thanks for your knowledge!
foreach($filters as &$filter){
preg_match ('#^\-(\d+)$#ism', $filter, $match);
if ($match[1]){
$filter = array(
'Under $'.intval($match[1]),
'product_price < '.intval($match[1])
);
}
...
}
return $filtering;
}
P.S.: I am not looking for a solution, because I could change the origin string into array, or I could change the foreach in to a pass by value and create a new array with the arrays like $newFilter[] = ... I am only curious
You can change it's type. Proof by construction:
<?php
header('Content-type:text/plain');
$arr = array(
'1',
'2',
);
foreach ($arr as &$filter) {
$filter = array($filter);
}
print_r($arr);
?>
Prints:
Array
(
[0] => Array
(
[0] => 1
)
[1] => Array
(
[0] => 2
)
)
You should change your foreach into
foreach($filters as $index => $filter)
and update your filter by doing
$filters[$index] = array(...);
I believe the $filter variable created by the foreach() statement is a copy of the data in the array and not a reference to it.