How to get data from big Array in PHP [duplicate] - php

This question already has answers here:
Implode a column of values from a two dimensional array [duplicate]
(3 answers)
Closed 7 months ago.
I have an array that contains player data. This array changes according to the number of players. The array looks like this:
Array
(
[0] => Array
(
[Id] => 0
[Name] => Playername1
[Frags] => -3
[Time] => 339
[TimeF] => 05:39
)
[1] => Array
(
[Id] => 0
[Name] => Playername2
[Frags] => 0
[Time] => 7
[TimeF] => 00:07
)
)
I want to get from this array from each player only the player name [name]. How do I do this? The output should be a string that looks something like this: Playername1, Playername2
I have not found anything on the Internet or on YouTube. The answer is certainly simple and obvious, but I have not found it.
Im using PHP 8.0.13.

$names = implode(',', array_column($arr, 'name'));
echo $names;
array_column: return the values from a single column in the input array.
implode: Join array elements with a string.

try something like this:
$player_names = '';
foreach($your_array as $key => $value){
$player_names .= $value['Name'].', ';
// this should concatenate all the player names
}

Related

How do you combine data from multiple loops into the same numeric key in a multidimensional array? [duplicate]

This question already has answers here:
Two arrays in foreach loop
(24 answers)
Closed 2 years ago.
I would like to collate data from multiple different data sources into one numeric array using foreach loops, however I am having some trouble building my array in the expected format. I would like to keep the key numeric.
For example, if I had two data sources: $fruit_data and $flavor_data and my code was:
foreach($fruit_data as $fruit){
$fruits[]['name'] = $fruit['name'];
}
foreach($flavor_data as $flavor){
$fruits[]['flavor'] = $flavor['taste'];
}
The data is added to the array with separate numeric keys, like this:
Array
(
[0] => Array
(
[name] => Example Name 1
)
[1] => Array
(
[flavor] => Example Flavor 1
)
[2] => Array
(
[name] => Example Name 2
)
[3] => Array
(
[flavor] => Example Flavor 2
)
)
However, my desired output is to display the data under the same numeric key, like this:
Array
(
[0] => Array
(
[name] => Example Name 1
[flavor] => Example Flavor 1
)
[1] => Array
(
[name] => Example Name 2
[flavor] => Example Flavor 2
)
)
Could somebody please explain where I am going wrong, and if possible, link me to a resource that explains how to overcome this issue? It may be that I have a fundamental misunderstanding of multidimensional arrays, but I cannot seem to find any references to this issue.
Any help is much appreciated.
foreach($fruit_data as $index => $fruit){
$fruits[] = [
'name' => $fruit['name'],
'flavor' => $flavor_data[$index]['taste']
];
}
Same as
foreach($fruit_data as $index => $fruit){
$fruits[] = [
'name' => $fruit_data[$index]['taste'],
'flavor' => $flavor_data[$index]['taste']
];
}

Convert onedimensional array into multidimensional array in php [duplicate]

This question already has answers here:
GROUP_CONCAT comma separator - MySQL
(3 answers)
Closed 2 years ago.
I have an array with film information and the times when they will be shown in the cinema. each showing is another result, so one film can be in the array multiple times. I want to combine duplicate film entries into one and put all shows in another dimension in the new array. The formatting is this:
Array (
[title] => title
[synopsis] => synopsis
[poster] => poster
[cast] => cast
[director] => director
[length] => length
[rating] => rating
[datetime] => datetime )
Should be formatted into:
Array (
[title] => title
[synopsis] => synopsis
[poster] => poster
[cast] => cast
[director] => director
[length] => length
[rating] => rating
[datetime] => Array
( [0] => datetime0
[1] => datetime1
... )
)
Has anyone an idea how to combine it after "title" and put all entries for datetime in a new dimension.
Thank for your help!
Suppose that title is unique (no two movies with the same title). Then this would work:
$newArray = [];
foreach ($array as $element) {
if (array_key_exists($element['title'], $newArray)) {
$newArray[$element['title']]['datetime'][] = $element['datetime'];
} else {
$element['datetime'] = [$element['datetime']];
$newArray[$element['title']] = $element;
}
}
$newArray = array_values($newArray);
However, as other comments pointed out, this is not an optimal solution, and you may want to think about the database structure or use something like CONCAT in SQL to return list of dates separated by a symbol, then use explode in PHP.

How to make array unique by one value and others in comma separated? [duplicate]

This question already has answers here:
Group subarrays by one column, make comma-separated values from other column within groups
(2 answers)
Closed 3 years ago.
Here is the array which I have,
Array
(
[0] => Array
(
[number] => 2
[name] => ABC
)
[1] => Array
(
[number] => 3
[name] => ABC
)
[2] => Array
(
[number] => 1
[name] => XYZ
)
[3] => Array
(
[number] => 2
[name] => XYZ
)
)
what I want is...
Array
(
[0] => Array
(
[name] => XYZ
[number] => 1,2
)
[1] => Array
(
[name] => ABC
[number] => 2,3
)
)
it should be unique by name.
And numbers of particular name will be in comma separated.
please help me guys
Thanks in advance
You can do this in one loop but I prefer to do it in two loops as it will be easier to get the correct output with implode than adding commas and then removing them again.
Loop the array and build an associative array and make an array to collect the numbers.
Then loop again and implode the numbers to a string.
foreach($arr as $sub){
$res[$sub['name']]['name'] = $sub['name'];
$res[$sub['name']]['number'][] = $sub['number'];
}
foreach($res as &$sub){
$sub['number'] = implode(",", $sub['number']);
}
$res = array_values($res);
var_dump($res);
https://3v4l.org/PbGsu
You can use array_map, array_key_exists, array_values to get the desired results
$res = [];
array_map(function($v) use (&$res){
array_key_exists($v['name'], $res) ?
($res[$v['name']]['number'] = $res[$v['name']]['number'].','.$v['number'])
:
($res[$v['name']] = ['number' => $v['number'],'name' => $v['name']])
;
}, $arr);
$res = array_values($res);
Live Demo
To use
array_merge()
function.
If suppose your key values are same, your key and values are overwrites after merge your array.

convert array into array to string is possible..? [duplicate]

This question already has answers here:
Implode a column of values from a two dimensional array [duplicate]
(3 answers)
Closed 6 years ago.
How to convert array within array to string, that means I am having a one result set having value of country id but the result set will be in array within array.
Something like below code :
Array
(
[0] => Array
(
[country_id] => 7
)
[1] => Array
(
[country_id] => 8
)
[2] => Array
(
[country_id] => 9
)
[3] => Array
(
[country_id] => 10
)
[4] => Array
(
[country_id] => 1
)
[5] => Array
(
[country_id] => 2
)
[6] => Array
(
[country_id] => 3
)
[7] => Array
(
[country_id] => 4
)
[8] => Array
(
[country_id] => 5
)
)
I want that country list into one string like 7,8,9,10,1,2,3,4,5 but without looping..
Anyone have idea please let me know...?
You can use array_column() and implode() function to do this.
Here is how you can do it,
$values=array_column($array,"country_id");
$country_string=implode($values);
array_column() returns the values from a single column of the input,
identified by the column_key(country_id).
implode() returns a string containing a string representation of all the array elements in the same order, with the glue string between
each element.
implode() can have two arguments, first as glue by which you want to join the elements and second as the array of elements. If first argument is not given then default glue is ",".
Use array_column and implode for (PHP 5 >= 5.5.0, PHP 7) as
$data = array_column($records, 'country_id');
echo implode(",",$data);
try this,
$newarray = array();
foreach ($array as $item) {
$newarray[] = $item['country_id'];
}
echo implode(",",$newarray);
i hope it will be helpful.

codeigniter flatten array of query result [duplicate]

This question already has answers here:
Is there a function to extract a 'column' from an array in PHP?
(15 answers)
Closed 7 months ago.
I'm using a query in Codeigniter to return the ids of all the rows that belong to a user.
$this->db->select('id');
$this->db->where('user_id', 99);
$query = $this->db->get('my_table');
return $query->result_array();
This returns
Array ( [0] => Array ( [id] => 8 ) [1] => Array ( [id] => 7 ) [2] => Array ( [id] => 6 ) )
Is it possible to return a flat array like
Array ( [0] => 8 [1] => 6 [2] => 7 )
?
The CodeIgniter documentation (most particularly, query results) doesn't list anything that will produce a flat array result (like the PDO::FETCH_COLUMN mode provided for PDOStatement::fetchAll). As such, array results will need to be flattened in your code, such as with a foreach loop:
$flat = array();
foreach($query->result_array() as $row) {
$flat[] = $row['id'];
}
or with the special purpose array_column:
array_column($query->result_array(), 'id');
or with the general purpose array_reduce:
array_reduce(
$results,
fn ($accum, $row) => array_merge($accum, [$row['id']]),
[]);
If you're to lazy to add few lines each time you select one column, you would need to tweak CodeIgniter. Like adding some option or returning flattened array when single column is selected. I would suggest adding an option
Following can be another way of dong it. I don't know what is the advantage of it over the accepted answer.
Let's say you are storing output of function in $result. Then you can do as following:
array_unshift($result, null);
$transposed = call_user_func_array("array_map", $result);
print_r($transposed);
It will print
Array( [0] => Array ( [0] => 8 [1] => 6 [2] => 7 ))
And you can access what you want by $transposed[0]
Array ( [0] => 8 [1] => 6 [2] => 7 )

Categories