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 )
Related
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().
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.
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.
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.
This question already has answers here:
How to re-index all subarray elements of a multidimensional array?
(6 answers)
Closed 2 years ago.
I am trying to filter and reindex this array. My original array is $_SESSION['ShowingRequests'].
I've tried
array_values(array_filter($_SESSION['ShowingRequests']))
and
array_values(array_filter($_SESSION['ShowingRequests']['ListingKey']))
array_values(array_filter($_SESSION['ShowingRequests']['Key']))
but it won't reach the second level of the array.
I want it to go from this
Array
(
[ListingKey] => Array
(
[1] => 97826889139
[2] => 97820967049
[4] => 97825243774
[5] => 97824864611
)
[Key] => Array
(
[1] => 2
[2] => 3
[4] => 5
[5] => 6
)
)
to this
Array
(
[ListingKey] => Array
(
[0] => 97826889139
[1] => 97820967049
[2] => 97825243774
[3] => 97824864611
)
[Key] => Array
(
[0] => 2
[1] => 3
[2] => 5
[3] => 6
)
)
PHP arrays are not indexed, because they are not real arrays. They are in fact ordered hashmaps and as such you should not really care about the keys here. Iterating over these arrays is trivial and does not require using array_values at all.
foreach ($_SESSION['ShowingRequests']['ListingKey'] as $key => $value) {
echo "$key => $value\n";
}
Would give you...
1 => 97826889139
2 => 97820967049
4 => 97825243774
5 => 97824864611
Where you get the name of the key and the value for each element in the array using the foreach construct.
In any case you have to remember that both array_values and array_filter are non-destructive functions. They return a new array. They do not modify the array by reference. As such you must assign the return value if you want to modify the existing array. They also do not work recursively.
$_SESSION['ShowingRequests']['ListingKey'] = array_values(array_filter($_SESSION['ShowingRequests']['ListingKey']));
$_SESSION['ShowingRequests']['Key'] = array_values(array_filter($_SESSION['ShowingRequests']['Key']));
$_SESSION['ShowingRequests'] = array_values(array_filter($_SESSION['ShowingRequests']));
Is your issue to assign the filtered values back to the same key?
foreach (['ListingKey', 'Key'] as $key)
{
$_SESSION['ShowingRequests'][$key] = array_values(
array_filter($_SESSION['ShowingRequests'][$key])
);
}
Here some demonstration how it works with a helper function just to make that more visible
function array_filter_values($var) {
return array_values(array_filter($var));
}
foreach (['ListingKey', 'Key'] as $key)
{
$_SESSION['ShowingRequests'][$key] =
array_filter_values($_SESSION['ShowingRequests'][$key])
;
}
Here is an example without that helper function but with an alias of which I had thought it might make that more easy to understand but apparently not:
foreach (['ListingKey', 'Key'] as $key)
{
$var = &$_SESSION['ShowingRequests'][$key];
$var = array_values(array_filter($var));
unset($var);
}
This example code is using an alias to the variable you want to change (here the part of the array you want to change). This probably makes it more visible how it works. Because it is an alias, unset is used to remove the alias, it should not be re-used in the next iteration or after the iteration has finished.