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

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.

Related

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

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
}

Create a multidimensional array based on number of values [duplicate]

This question already has answers here:
Transpose a PHP multidimensional array with predefined keys
(3 answers)
How to transpose a multidimensional multi-file upload submission and maintain associative keys?
(4 answers)
Closed 1 year ago.
i have an array that i get from a form with alot of fields, i need to order those fields under an array and that array under the ''main'' array. Ill post what i have, and what i need to get.
WHAT I HAVE:
Array
(
[perfil_area1] => Array
(
[0] => a2
[1] => a3
)
[perfil_years] => Array
(
[0] => 2
[1] => 4
)
[perfil_function] => Array
(
[0] => f1
[1] => f4
)
[perfil_obs] => Array
(
[0] => teste1
[1] => teste2
)
[perfil_company] => Array
(
[0] => emp1
[1] => emp2
)
)
This is what i need to be so i can turn it into a query:
What i need
Array
(
[0] =>
(
[perfil_area1] => a2
[perfil_years] => 2
[perfil_function] => f1
[perfil_obs] => teste1
[perfil_company] => emp1
)
[1] =>
(
[perfil_area1] => emp2
[perfil_years] => 2
[perfil_function] => f4
[perfil_obs] => 4
[perfil_company] => a3
)
)
i have tried with 2 foreach but i didnt manage to get it done. I have read Create a multidimensional array in a loop , how to create multidimensional array using a foreach loop in php? , create multidimensional array using a foreach loop , Converting an array from one to multi-dimensional based on parent ID values and some more but i still cant do it. Any tips on how to create it?
You just need to loop over the input array and build the new array
$new = [];
foreach ($in as $key=>$arr) {
$new[0][$key] = $arr[0];
$new[1][$key] = $arr[1];
}
<?php
$result = [];
for ($i=0; $i<count(reset($array)); $i++) {
$result[] = array_combine(array_keys($array), array_column($array, $i));
}
Please read the manual for more details about array_combine(), array_keys() and array_column().

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.

Reduce down level of multidimensional array in PHP [duplicate]

This question already has answers here:
Is there a function to extract a 'column' from an array in PHP?
(15 answers)
Closed 6 months ago.
I'm wondering what the most efficient way to reduce this array down by a level, ideally without loops in PHP. It's a result from mysqli_fetch_all().
Array
(
[0] => Array
(
[ID] => 648546
)
[1] => Array
(
[ID] => 648552
)
[2] => Array
(
[ID] => 650046
)
[3] => Array
(
[ID] => 652732
)
[4] => Array
(
[ID] => 652738
)
[5] => Array
(
[ID] => 652756
)
)
The result I would like is
array(648546,648552,650046,652732,...)
The simple query example it comes from is something as easy as:
SELECT mytable.ID FROM mytable WHERE status =1
This should do it for PHP 5.5+
$result = array_column($array, 'ID');
You can use array_map():
$new_array = array_map(function($v){return $v['ID'];}, $old_array);
You might try this:
SELECT GROUP_CONCAT(mytable.ID)
FROM mytable
WHERE status = 1
GROUP BY status
It should return 1 row with the ID as a comma separated list.

Change the content of an array to be more efficient [duplicate]

This question already has answers here:
PHP array replace numbers with keys
(2 answers)
Closed 6 years ago.
When doing a print_r on my array, I get the following output;
Array
(
[0] => Array
(
[id] => 178
[name] => Briar Price
)
[1] => Array
(
[id] => 90
[name] => Bradley Kramer
)
[2] => Array
(
[id] => 508
[name] => Calvin Yang
)
[3] => Array
(
[id] => 457
[name] => Charles Valenzuela
)
... and so on
How can I modify the array to look like this;
Array
(
[178] => Briar Price
[90] => Bradley Kramer
[508] => Calvin Yang
[457] => Charles Valenzuela
... and so on
)
I just want to make the ID the key for the value name. I always have issues when it comes to arrays reordering.
Pass third parameter to array_column to make its key as
$array = array_column($users, 'name', 'id');
print_r($array);
Use foreach() -
$newArr = array();
foreach ($your_array as $key => $val) {
$newArr[$val['id']] = $val['name'];
}
print_r($newArr) // desired output
I'd use array_combine which attaches new keys to values
$results = [
['id'=>1,'name'=>'John'],['id'=>2,'name'=>'Jane'],
];
$results = array_combine(
array_column($results,'id'), //use 'id' column as keys
array_column($results,'name') //use 'name' column as values
);
//now $results is [1=>'John', 2=>'Jane']
You can do it using array_column and array_combine PHP function without applying custom logic.
Here is how you do it,
<?php
$keys=array_column($mainarray,'id');
$values=array_column($mainarray,'name');
$finalarray=array_combine($keys,$values);
$finalarray will be your desired result.
array_combine creates an array by using one array for keys and another for its values.
array_column returns the values from a single column in the input array.

Categories