This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
In PHP, how do you change the key of an array element?
This the array
Array
(
[0] => Array
(
[id] => 1
[due_date] => 2011-09-23
[due_amount] => 10600.00
)
[1] => Array
(
[id] => 2
[due_date] => 2011-10-23
[due_amount] => 10600.00
)
[2] => Array
(
[id] => 3
[due_date] => 2011-11-23
[due_amount] => 10600.00
)
)
how to change id to u_id in this array?
Regards
array_walk_recursive($array, 'changeIDkey');
function changeIDkey($item, &$key)
{
if ($key == 'id') $key = 'u_id';
}
PHP Manual: array_walk_recursive
EDIT
This will not work for the reason #salathe gave in the Comments below. Working on alternative.
ACTUAL ANSWER
function changeIDkey(&$value,$key)
{
if ($value === "id") $value = "u_id";
}
$new = array();
foreach ($array as $key => $value)
{
$keys = array_keys($value);
array_walk($keys,"changeIDkey");
$new[] = array_combine($keys,array_values($value));
}
var_dump($new); //verify
Where $array is your input array. Note that this will only work with your current array structure (two-dimensions, changes keys on only second dimension).
The loop iterates through the inner arrays changing "id" to "u_id" in the keys and then recombines the new keys with the old values.
foreach( $array as &$element ) {
$element['u_id'] = $element['id'];
unset( $element['id'] );
}
Related
This question already has answers here:
Filter/Remove rows where column value is found more than once in a multidimensional array
(4 answers)
Closed 9 months ago.
Is it possible to remove sub arrays, if the array item at position 0 of that sub array matches subsequent items?
For example;
Array ( [0] => Array ( [0] => 1234 [1] => XX000 )
[1] => Array ( [0] => 1234 [1] => XX001 )
[2] => Array ( [0] => 1234 [1] => XX002 )
)
Would be adjusted to output;
Array ( [0] => Array ( [0] => 1234 [1] => XX000 ) )
function my_array_filter($arr){
$exist = [];
return array_filter($arr, function($element){
if( ! array_key_exist($element[0], $exist)){
$exist[$element[0]] = true;
return true;
}
return false;
});
}
Maybe it is possible with some arcane usage of array functions and callback, but I prefer keeping things simple whenever possible, so I understand my own solutions years later.
So why not program it?
$ORG = [ [ 1234, 'XX000' ],
[ 1234, 'XX001' ],
[ 1234, 'XX002' ],
[19987, 'XX000'] ];
$NEW = [];
$USEDKEYS = [];
foreach ($ORG as $one){
if (in_array($one[0], $USEDKEYS)) {
// skip.
} else {
$NEW[] = $one;
$USEDKEYS[] = $one[0];
}
}
unset ($USEDKEYS, $ORG);
var_dump ($NEW);
Always the way, I've found out the solution after posting this ($query being the multi-dimensional array);
$newArr = array();
foreach ($query as $val) {
$newArr[$val[0]] = $val;
}
$query = array_values($newArr);
Well this has been a headache.
I have two arrays;
$array_1 = Array
(
[0] => Array
(
[id] => 1
[name] => 'john'
[age] => 30
)
[1] => Array
(
[id] => 2
[name] => 'Amma'
[age] => 28
)
[2] => Array
(
[id] => 3
[name] => 'Francis'
[age] => 29
)
)
And another array
array_2 = = Array
(
[0] => Array
(
[id] => 2
[name] => 'Amma'
)
)
How can I tell that the id and name of $array_2 are the same as the id and name of $array_1[1] and return $array_1[1]['age']?
Thanks
foreach($array_1 as $id=>$arr)
{
if($arr["id"]==$array_2[0]["id"] AND $arr["name"]==$array_2[0]["name"])
{
//Do your stuff here
}
}
Well you can do it in a straightforward loop. I am going to write a function that takes the FIRST element in $array_2 that matches something in $array_1 and returns the 'age':
function getField($array_1, $array_2, $field)
{
foreach ($array_2 as $a2) {
foreach ($array_1 as $a1) {
$match = true;
foreach ($a2 as $k => $v) {
if (!isset($a1[$k]) || $a1[$k] != $a2[$k]) {
$match = false;
break;
}
}
if ($match) {
return $a1[$field];
}
}
}
return null;
}
Use array_diff().
In my opinion, using array_diff() is a more generic solution than simply comparing the specific keys.
Array_diff() returns a new array that represents all entries that exists in the first array and DO NOT exist in the second array.
Since your first array contains 3 keys and the seconds array contains 2 keys, when there's 2 matches, array_diff() will return an array containing the extra key (age).
foreach ($array_1 as $arr) {
if (count(array_diff($arr, $array_2[1])) === 1) {//meaning 2 out of 3 were a match
echo $arr['age'];//prints the age
}
}
Hope this helps!
I assume you want to find the age of somebody that has a known id and name.
This will work :
foreach ($array_1 as $val){
if($val['id']==$array_2[0]['id'] && $val['name']==$array_1[0]['name']){
$age = $val['age'];
}
}
echo $age;
Try looking into this.
http://www.w3schools.com/php/func_array_diff.asp
And
comparing two arrays in php
-Best
This question already has answers here:
How to Flatten a Multidimensional Array?
(31 answers)
Closed 9 years ago.
I have an array like the following:
Array
(
[0] => Array
(
[0] => 1
[1] => 2
[2] => 3
)
[1] => Array
(
[0] => 3
)
[2] => Array
(
[0] => 4
)
)
Now I want each array value into one single array. How do I do it?
Thanks in advance.
// PHP >= 5.3:
function array_value_recursive($key, array $arr){
$val = array();
array_walk_recursive($arr, function($v, $k) use($key, &$val){
if($k == $key) array_push($val, $v);
});
return $val;
}
You can recursively parse the array with a function:
$multiDimArr = array(...);
function getSingleArray( $multiDimArr ) {
$singleArray = array();
foreach($multiDimArr as $row) {
if( is_array($row) ) {
getSingleArray($row); // recursive call -> row it cand be also multi dimensional
}
else {
$singleArray[] = $val;
}
}
return $singleArray;
}
I really hope this will help!!
This question already has answers here:
Is there a function to extract a 'column' from an array in PHP?
(15 answers)
Closed 11 months ago.
I have an array called $friends with names and ids, gotten from the Facebook graph API.
If I print it, it look something like this:
Array (
[0] => Array (
[name] => Tom
[id] => 21)
[1] => Array (
[name] => Bob
[id] => 22)
)
How do I retrieve all Keys (ids) and create a new array like this one?
Array ( [0] => 21 [1] => 22 )
$ids = array_map(function ($friend) { return $friend['id']; }, $friends);
Note, uses PHP 5.3+ anonymous function syntax.
You can use a simple foreach.
$ids = array();
foreach($friends as $friend)
$ids[] = $friend['id'];
foreach ($friends as $key => $value) {
$newFriends[$key] = $value['id'];
}
$arFinal = array();
foreach ($friends as $key => $val){
$arFinal[$key] = $val['id'];
}
This question already has answers here:
How can you make a multidimensional array unique? [duplicate]
(6 answers)
Closed 10 years ago.
I have a multidimensional array which I need to be sorted with uniqueness as I have duplicated records, so I need array_unique to go through the array and remove duplicates by the value, e.g.
Array
(
[0] => Array
(
[id] => 324
[time_start] => 1301612580
[level] => 0.002
[input_level] => 0.002
)
[1] => Array
(
[id] => 325
[time_start] => 1301612580
[level] => 0.002
[input_level] => 0.002
)
[2] => Array
(
[id] => 326
[time_start] => 1301612580
[level] => 0.002
[input_level] => 0.002
)
)
There are duplicated time_start, which they are all the same, also level and input_level but they are not to be affected, only if there are matching time_start it should remove it and process the whole array (the array is bigger than you think, but I just posted a small example of the array). Should remove dupes and return like this:
Array
(
[0] => Array
(
[id] => 324
[time_start] => 1301612580
[level] => 0.002
[input_level] => 0.002
)
)
Questions I've found that didn't work:
reformat multidimensional array based on value
Delete element from multidimensional-array based on value
$input = array( /* your data */ );
$temp = array();
$keys = array();
foreach ( $input as $key => $data ) {
unset($data['id']);
if ( !in_array($data, $temp) ) {
$temp[] = $data;
$keys[$key] = true;
}
}
$output = array_intersect_key($input, $keys);
or
$input = array( /* your data */ );
$temp = $input;
foreach ( $temp as &$data ) {
unset($data['id']);
}
$output = array_intersect_key($input, array_unique($temp));
$temp = array();
array_filter($yourArray, function ($v) use (&$temp) {
if (in_array($v['time_start'], $temp)) {
return false;
} else {
array_push($temp, $v['time_start']);
return true;
}
});
Uses array_filter() which will filter an array based on the result of a callback (I used an anonymous function which can be used since PHP 5.3). The time_start values are collected into a temporary array.
I think you'll just have to walk it:
$usedVals = array();
$outArray = array();
foreach ($targetArray as $arrayItem)
{
if (!in_array($arrayItem['time_start'],$usedVals))
{
$outArray[] = $arrayItem;
$usedVals[] = $arrayItem['time_start'];
}
}
return $outArray;
$uniq = array();
foreach($no_unique as $k=>$v) if(!isset($uniq[$v['time_start']])) $uniq[$v['time_start']] = $v;
$uniq = array_values($uniq);