PHP, array manipulation to get keys with all same name - php

I have this array posting to my controller:
Array
(
[id] => Array
(
[0] => 95
[1] => 69
)
)
I want:
Array(
[id] => 95
[id] => 69
)
As I am using CodeIgniter's $this->db->delete() function and it takes the array key value as the column for the WHERE clause. I have this code at the moment:
foreach($ids as $k => $v){
$formatIds['id'] = $v;
}
Which just gives me one of the rows and not the rest.
I then tried:
foreach($ids as $k => $v){
$formatIds['id'][] = $v;
}
But this gives me a MultiDimensional array...

The answer to your question is "not possible": array keys must always be unique.
The answer to what you're trying to do is to use where_in():
$names = array(95,69);
$this->db->where_in('id', $names);
$this->db->delete('mytable');

Related

Remove duplicate rows from array even if their element ordering is different

in PHP how to get this unique of array ?
$originalArray = [[2,48],[48,2],[19,31],[31,19]];
I want to get
Array
(
[0] => Array
(
[0] => 2
[1] => 48
)
[2] => Array
(
[0] => 19
[1] => 31
)
)
I tried with array_unique($array,SORT_REGULAR) but still won't work.
Is there other function to achieve this ?
Similiar to this technique. Use sorted, stringified keys to build the filtered result.
Code: (Demo)
$array = [[2,48],[48,2],[19,31],[31,19]];
$result = [];
foreach ($array as $row) {
sort($row);
$result[json_encode($row)] ??= $row; // just = will also work
}
var_export(array_values($result));

Flatten an subarray and transform its values in key and also in value of the new array using PHP

I have following multidimensional array:
Array (
[0] => Array
(
[0] => 2007
[1] => 318
)
[1] => Array
(
[0] => 2001
[1] => 307
)
[2] => Array
(
[0] => 1993
[1] => 306
)
[3] => Array
(
[0] => 2011
[1] => 285
)
)
and would like to transform it in:
Array (
[2007] => 318,
[2001] => 307,
[1993] => 306,
[2011] => 285
)
Also the value of key[0] of the subarray will be the key of the new array and value of key[1] of the subarray will be the value of the new array.
I tried that, but only success:
$newArray = array();
foreach ($chart05 as $items) {
$newArray = array_merge($newArray, $items);
}
and this as well:
foreach($array as $k => $v){
foreach($v as $value) {
$newArray[] = $value;
}
but none give me the expect result.
Then I would like to transform the new array in a string just like that:
[2007,318], [2001,307], [1993,306], [2011,285]
Here I'm not sure, but I think implode would work. What do you guys think?
I would appreciate any help!!!
$newArray = array();
foreach ($chart05 as $items) {
$newArray[$items[0]] = $items[1];
}
Wil create the array structure you want.
However for the string output, i believe you dont want to change the original array, just json_encode it:
echo json_encode($chart05);
Live example: http://codepad.viper-7.com/tYxECS

Search in Array of Arrays

I have arrays like this:
Array
(
[license_id] => 2
[email_address] => alib#email.com
[user_id] => 2
[first_watch] =>
)
Array
(
[license_id] => 1
[email_address] => user1#email.com
[user_id] =>
[first_watch] =>
)
These arrays will be embedded in an array, so the result is an array of arrays.
I need to search within these items for a specific user_id.
so for instance i want to find out if the big array includes an array that has the user_id = 2 and return the key of that array.
Array
(
[0] => Array
(
[license_id] => 2
[email_address] => alib#email.com
[user_id] => 2
[first_watch] =>
)
[1] => Array
(
[license_id] => 1
[email_address] => user1#email.com
[user_id] =>
[first_watch] =>
)
)
What I want from this example would the key, [0] if I'm looking for 2 (user_id). I'll be always looking for a user_id so that's fixed.
I used foreach to loop through items and in_array() to find the item, but the result is not always as I expect, sometimes searching for something that doesn't exist will still return a key.
You guys have any suggestions on achieving this?
PHP >= 5.5.0
Extract the user_id column and search:
$key = array_search(2, array_column($array, 'user_id'));
PHP < 5.5.0
Map and get user_id:
$key = array_search(2, array_map(function($v) { return $v['user_id']; }, $array));
Or loop and check:
foreach($array as $k => $v) {
if($v['user_id'] == 2) {
$key = $k;
break;
}
}
I would do this:
//my_array being your multidimensional array
//my_id being the id you're looking for
$index = null;
for($i=0;$i<count($my_array);$i++)
{
//is the id in this sub array?
if($my_array[$i]['user_id'] == $my_id)
{
//get the index you're searching for
$index = $i;
}
}
//check if an index was found
if($index != null)
{
//display the index you're searching for
echo $index;
}
It's a little bit long but it allows you to do add stuff to the code if you need to.

split a multidimentional array into new a set of simple arrays by key in PHP

I have a multidimensional array that I would like to split by key, Ideally I would like to create new named arrays dynamically from the key values of the multidimensional array.
logically, I assume I need to get the keys, and then for each key loop through the multidimensioal array and push the values of corresponding key for that iteration onto the new array.
each inner array is quite large, and ideally i would like to set this up so that if that array changes its number of pairs this will still function.
I feel like I know some of the ingredients here, but just can't seem to put it together.
Example array:
$data = Array(
[0] => Array
(
[count] => 0
[id] => 221
[title] => Home
[latitude] => -34.0284224
[longitude] => 18.46636710000007
),
[1] => Array
(
[count] => 1
[id] => 321
[title] => office
[latitude] => -34.0284224
[longitude] => 18.46636710000007
),
[2] => Array
(
[count] => 2
[id] => 124
[title] => storage
[latitude] => -34.0284224
[longitude] => 18.46636710000007
)
)
and what I'd like to produce is :
$count = array(0,1,2);
$id = array(221,321,124);
$title = array('home','office','storage');
etc etc
any and all help will be massively appreciated.
Variable variables seem to be what you're looking for:
foreach($data as $element) {
foreach($element as $key => $value) {
if(!isset($$key)) {
$$key = array();
}
array_push($$key, $value);
}
}
If you're using PHP >=5.5, then array_column() can do this for you:
$count = array_column($data, 'count');
$id = array_column($data, 'id');
$title = array_column($data, 'title');
To make it more generic:
foreach($data[0] as $key => $value) {
$$key = array_column($data, $key);
}
but the danger here is that you don't necessarily know the names of the variables that you're creating
so a more-generic-still
$newArray = array();
foreach($data[0] as $key => $value) {
$newArray[$key] = array_column($data, $key);
}
may be more workable

Sum multidimensional associative array values while preserving key names

There are many nice Q&A on Stackoverflow on how to take a multidimensional associative array and sum values in it. Unfortunately, I can't find one where the key names aren't lost.
For example:
$arr=array(
array('id'=>'1', 'amount'=>'5'),
array('id'=>'1', 'amount'=>'5'),
array('id'=>'2', 'amount'=>'1'),
array('id'=>'2', 'amount'=>'3')
);
I want the resulting array to look like this:
$result=array(
array('id'=>'1', 'amount'=>'10'),
array('id'=>'2', 'amount'=>'4')
);
Unfortunately the only thing I can figure out how to do is this:
$result = array();
foreach($arr as $amount){
if(!array_key_exists($amount['id'], $arr))
$result[$amount['id']] =0;
$result[$amount['id']] += $amount['amount'];
}
Which when echo'd as follows produces (notice the lack of the keys' words "id" and "amount"):
foreach($result as $id => $amount){
echo $id."==>".$amount."\n";
}
1==>10
2==>4
This is just to show that you already had the data you originally needed, though, the answer you accepted is a better way to deal with it.
You have the following to start with right?
$arr = array(
array('id'=>'1', 'amount'=>'5'),
array('id'=>'1', 'amount'=>'5'),
array('id'=>'2', 'amount'=>'1'),
array('id'=>'2', 'amount'=>'3')
);
Output
Array
(
[0] => Array
(
[id] => 1
[amount] => 5
)
[1] => Array
(
[id] => 1
[amount] => 5
)
[2] => Array
(
[id] => 2
[amount] => 1
)
[3] => Array
(
[id] => 2
[amount] => 3
)
)
Then you run it through the following algorithm:
$summedArr = array();
foreach ($arr as $amount) {
$summedArr['amount'][$amount['id']] += $amount['amount'];
$summedArr['id'][$amount['id']] = $amount['id'];
}
Now, disregarding the Notice warnings that are produced since you are referencing indexes that don't yet exist, this outputs the following:
Output
Array
(
[amount] => Array
(
[1] => 10
[2] => 4
)
[id] => Array
(
[1] => 1
[2] => 2
)
)
Do you see the keys, yet? Because I do.
Now iterate over the array:
foreach ($summedArr as $key => $value) {
echo $k . "==>" . $v . "\n";
}
Output
amount==>Array
id==>Array
That's not what you want, though. You want:
foreach ($summedArr as $key => $arr) {
foreach ($arr as $v) {
echo $key . "==>" . $v;
}
}
Why not use that method, and then reconstruct the array you want at the end?
$results = array();
foreach ($arr as $id=>$amount) {
$results[] = array('id' => $id, 'amount' => $amount);
}
Any other way of doing this would be more computationally expensive.

Categories