This question already has answers here:
Merge two 2d arrays by shared column value
(6 answers)
Closed last month.
I would like to create a PHP array that will end up looking like this:
idPlayer namePlayer Points
1 John 20
2 Sam 25
3 Ben 22
But I would like to append the values not all at once:
First append the idPlayer and namePlayer
Then append the points for that idPlayer (I would have a $idPlayer variable to use each time I loop)
How could I do this in PHP?
I was thinking:
$myArray['idPlayer'] = "1";
$myArray['namePlayer'] = "John";
$myArray['Points'] = "20"
And then, how would I tell the array to go to the next row?
// output array
$myArray = array();
// your loop
while (something) {
// make an array for this iteration
$itarr = array();
// put stuff in it
$itarr['idPlayer'] = "1";
$itarr['namePlayer'] = "John";
$itarr['Points'] = "20"
// append it to output array using standard array indexing
$myArray[] = $itarr;
// OR, your own index
$myArray[$itarr['idPlayer']] = $itarr;
}
I dont know why you want to achieve such thing. But consider this example:
// like player table array initial
$players = array(
array(
'idPlayer' => 1,
'namePlayer' => 'John',
),
array(
'idPlayer' => 2,
'namePlayer' => 'Sam',
),
array(
'idPlayer' => 3,
'namePlayer' => 'Ben',
),
);
// data points to be added later (like points table)
$points = array(
array(
'idPlayer' => 1,
'Points' => 20,
),
array(
'idPlayer' => 2,
'Points' => 25,
),
array(
'idPlayer' => 3,
'Points' => 22,
),
);
$myArray = array();
foreach($players as $key => $value) {
foreach($points as $index => $element) {
// if this particular id matches the record inside points table then merge
if($value['idPlayer'] == $element['idPlayer']) {
$myArray[] = array('idPlayer' => $value['idPlayer'], 'namePlayer' => $value['namePlayer'], 'Points' => $element['Points']);
}
}
}
Should output something like: (can be used in a tabular data)
Array
(
[0] => Array
(
[idPlayer] => 1
[namePlayer] => John
[Points] => 20
)
[1] => Array
(
[idPlayer] => 2
[namePlayer] => Sam
[Points] => 25
)
[2] => Array
(
[idPlayer] => 3
[namePlayer] => Ben
[Points] => 22
)
)
Use the idPlayer as index:
$players = [
1 => [
'namePlayer' => 'John',
'points' => 20,
],
5 => [
'namePlayer' => 'Seth',
'points' => 25,
],
13 => [
'namePlayer' => 'Ben',
'points' => 35,
],
];
var_dump($players);
http://codepad.viper-7.com/nSXmZF
In php <5.4 use array() instead of [] constructor.
Related
Is it possible to create a new array from the keys of another like following?
it is a dynamic array chk_values are dynamically changed depends on condition
Array
(
[actBtn] => update
[chkCount] => 5
[chk_1] => 2
[chk_2] => 3
[chk_3] => 2
[chk_4] => 3
[chk_5] => 3
)
and i want array like this for update database
$chckpoint = Array(
[chk_1] => 2
[chk_2] => 3
[chk_3] => 2
[chk_4] => 3
[chk_5] => 3)
Simply process the original array and only move to the new array where the key starts with chk_
$in = ['actBtn' => 'update',
'chkCount' => 5,
'chk_1' => 2,
'chk_2' => 3,
'chk_3' => 2,
'chk_4' => 3,
'chk_5' => 3
];
foreach($in as $k=>$v){
if ( strpos($k,'chk_') !== false ){ $chckpoint[$k] = $v; }
}
print_r($chckpoint);
RESULT
Array
(
[chk_1] => 2
[chk_2] => 3
[chk_3] => 2
[chk_4] => 3
[chk_5] => 3
)
You can simply take the input array and check for all keys beginning with chk_. If the key matches, take it to the new array.
$chckpoint = [];
foreach($input as $key => $value)
{
if(substr($key, 0, 4) == 'chk_') $chkpoint[$key] = $value;
}
I got the follwing array and I would like to retrieve the name by the id:
Array
(
[0] => Array
(
[id] => 1
[name] => john
)
[1] => Array
(
[id] => 2
[name] => mark
)
etc...
It is doable with double foreach loop and a conditional test, but is there a more elegant way?
Assuming that id is unique...
Long Version
$arr = [
['id'=1, 'name'='john'],
['id'=2, 'name'='mark'],
];
$lookup = [];
foreach($arr as $row) {
$id = $row['id'];
$name = $row['name'];
$lookup[$id] = $name;
}
// find name for id, 2
echo $lookup[2];
// ==> mark
Short Version
...see Progrock’s solution!
You can use array_column to map ids to names:
<?php
$arr = [
['id' => 1, 'name' => 'Rolf'],
['id' => 3, 'name' => 'Gary'],
['id' => 2, 'name' => 'Jimmy'],
];
$id_names = array_column($arr, 'name', 'id');
var_export($id_names);
print $id_names[3];
Output:
array (
1 => 'Rolf',
3 => 'Gary',
2 => 'Jimmy',
)Gary
I have an multidimensional array like this one:
Array
(
[0] => array('id'=>1,'name'=>'Agent 1','total'=>3)
[1] => array('id'=>2,'name'=>'Agent 2','total'=>3)
[2] => array('id'=>3,'name'=>'Agent 3','total'=>3)
[3] => array('id'=>1,'name'=>'Agent 1','total'=>6)
)
And I want to remove duplicate agents from this array and sum the total field to end up in a array like this:
Array
(
[0] => array('id'=>1,'name'=>'Agent 1','total'=>9)
[1] => array('id'=>2,'name'=>'Agent 2','total'=>3)
[2] => array('id'=>3,'name'=>'Agent 3','total'=>3)
)
I have tried array_unique but it only remove duplicates...
Try this code: sandbox code
Main idea of algorithm - caching key pairs in result array and further checking existence of them.
$array = [
0 => ['id' => 1, 'name' => 'Agent 1', 'total' => 3],
1 => ['id' => 2, 'name' => 'Agent 2', 'total' => 3],
2 => ['id' => 3, 'name' => 'Agent 3', 'total' => 3],
3 => ['id' => 1, 'name' => 'Agent 1', 'total' => 6],
];
$sumArray = [];
foreach ($array as $agentInfo) {
// create new item in result array if pair 'id'+'name' not exists
if (!isset($sumArray[$agentInfo['id'].$agentInfo['name']])) {
$sumArray[$agentInfo['id'].$agentInfo['name']] = $agentInfo;
} else {
// apply sum to existing element otherwise
$sumArray[$agentInfo['id'].$agentInfo['name']]['total'] += $agentInfo['total'];
}
}
// optional action to flush keys of array
$sumArray = array_values($sumArray);
print_r ($sumArray);
Try this,
$arrays = array_values(array_combine(array_map(function ($i) { return $i['id']; }, $array), $array));
print_r($arrays);
DEMO
assuming an id is unique you could use this
$array = array(
array('id' => 1, 'name' => 'Agent 1', 'total' => 3),
array('id' => 2, 'name' => 'Agent 2', 'total' => 3),
array('id' => 3, 'name' => 'Agent 3', 'total' => 3),
array('id' => 1, 'name' => 'Agent 1', 'total' => 6)
);
$array_ids = array();
foreach ($array as $key => $value) {
if (isset($array_ids[$value['id']])) {
$array[$array_ids[$value['id']]]['total'] += $value['total'];
unset($array[$key]);
}
else
{
$array_ids[$value['id']] = $key;
}
}
in this way you save the used id's into array $array_ids, with that you can easily check if an agent already exists in the array
In order to achieve the exact output you desire, you will need a nested loop.
$input = array(
0 => array('id'=>1,'name'=>'Agent 1','total'=>3),
1 => array('id'=>2,'name'=>'Agent 2','total'=>3),
2 => array('id'=>3,'name'=>'Agent 3','total'=>3),
3 => array('id'=>1,'name'=>'Agent 1','total'=>6)
);
// This is where we will save our result
$output = array();
foreach ($input as $item) {
// Used to determine if the current $item
// already exists in the $output array
$foundItem = false;
// Now we check the $item against every output entry
foreach ($output as &$entry) {
if ($entry["id"] == $item["id"]) {
// Since we found a match, let's add the
//current item's total to the output total.
$entry["total"] += $item["total"];
// Marking this as true will later prevent us
// from inserting the item to the output array twice
$foundItem = true;
}
}
// If the item was not found in the output array
// the $foundItem variable remains false
// Using ! to negate the boolean, we insert the item to the output array
if (!$foundItem) {
$output[] = $item;
}
}
Realize that this is not the only way to get the required output. This only is the simplest solution and can certainly be improved in many ways. However, I will leave that part up to you.
I have tried using array_reduce - Iteratively reduce the array to a single value using a callback function. And written a function according to the requirements. Hope this will help you.
<?php
$array = [
0 => ['id' => 1, 'name' => 'Agent 1', 'total' => 3],
1 => ['id' => 2, 'name' => 'Agent 2', 'total' => 3],
2 => ['id' => 3, 'name' => 'Agent 3', 'total' => 3],
3 => ['id' => 1, 'name' => 'Agent 1', 'total' => 6],
];
$result = array_reduce($array, function($temp, $item){
isset($temp[$item['id']])
? $temp[$item['id']]['total'] += $item['total']
: $temp[$item['id']] = $item;
return $temp;
}, []);
print_r($result);
?>
OUTPUT
Array
(
[1] => Array ( [id] => 1 [name] => Agent 1 [total] => 9 )
[2] => Array ( [id] => 2 [name] => Agent 2 [total] => 3 )
[3] => Array ( [id] => 3 [name] => Agent 3 [total] => 3 )
)
I have two arrays $array and $array2. I need to merge them on behalf of common key value i.e. entry_id.
Well I need to merge them is such a way that if the entry_id of array 1 matches with the entry_id of array2, it merges. If the entry_id doesn't match that array remains as it but it should be entered in the merged array. I have tried but i didn't get the desired results. If it is possible to do this without function?
Thanks in Advance.
Here is my code
<?php
$array = array(
array(
'title' => 'mytitleeee',
'entry_id' => 1000
),
array(
'title' => 'myt',
'entry_id' => 1001
),
array(
'title' => 'mytRRRR',
'entry_id' => 1003
),
array(
'title' => 'RUKES',
'entry_id' => 1004
)
);
$array2 = array(
array(
'author_id' => 'desc1',
'entry_id' => 1000
),
array(
'author_id' => 'desc2',
'entry_id' => 1001
),
array(
'author_id' => 'desc3',
'DAY' => 'MON',
'entry_id' => 1003
),
array(
'author_id' => 'desc7',
'DAY' => 'TUE',
'entry_id' => 1012
)
);
$x = array();
foreach($array as $value => $ans){
}
foreach($array2 as $value1 => $ans1){
}
if($ans1['entry_id']!= $ans['entry_id']){
$x = ($ans1);
echo"<pre>";
print_r($x);
}
You could apply this array_reduce call to the array_merge result:
$result = array_reduce(array_merge($array, $array2), function ($acc, $el) {
$key = $el['entry_id'];
$acc[$key] = isset($acc[$key]) ? $acc[$key] + $el : $el;
return $acc;
}, []);
$result will have the following for your sample data:
array (
1000 => array (
'title' => 'mytitleeee',
'entry_id' => 1000,
'author_id' => 'desc1',
),
1001 => array (
'title' => 'myt',
'entry_id' => 1001,
'author_id' => 'desc2',
),
1003 => array (
'title' => 'mytRRRR',
'entry_id' => 1003,
'author_id' => 'desc3',
'DAY' => 'MON',
),
1004 => array (
'title' => 'RUKES',
'entry_id' => 1004,
),
1012 => array (
'author_id' => 'desc7',
'DAY' => 'TUE',
'entry_id' => 1012,
),
)
How it works
First the two arrays are merged:
array_merge($array, $array2)
This just appends the elements of the second array after those of the first.
This array is then passed to array_reduce, which calls the callback function -- given as argument -- for each element.
Furthermore, that function also gets an accumulated value ($acc), which in the first call is [] (provided as final argument to reduce). Whatever the function returns becomes the accumulated value that is passed in the second function call (for the second element), ...etc. The final returned value becomes the return value of reduce.
So in this case the accumulated value is an associative array that is keyed by entry_id. If at a certain moment that key already exists, the current value is merged with the value that is already in $acc: this merge is done with the + operator. If the entry_id of the current element is not yet in $acc it is added to it.
This if...else is implemented with the ternary operator (... ? ... : ...).
The return$accstatement ensures that the the next time this callback is called (for the next element),$acc` is again that accumulated value.
I have 1 array that has the right values that I need but it is out of order. I then have another array with the same keys and it is in the right order but the values are not what I need.
Here is my first array with the correct values but is out of order:
Array
(
[countTotal] => 7268
[zip] =>
[yearName] =>
[countZipRadius] =>
[Acura] => 1334
[Cadillac] => 511
[Ford] => 5423
)
Here is my second array with the right order but the wrong values:
Array
(
[countZipRadius] => 0
[zip] => 1
[yearName] => 2
[Acura] => 3
[Cadillac] => 4
[Ford] => 5
[countTotal] => 6
)
I am trying to figure out a way to create a new array with the right values from array 1 but that is in the order of array 2.
I have been playing with it for awhile and cannot seem to get it.
Any help would be great.
Thanks!
$c = array();
foreach (array_keys($b) as $k) {
$c[k] = $a[k];
}
You could use php's array_multisort function:
$original = array(
'countTotal' => 7268,
'zip' => '',
'yearName' => '',
'countZipRadius' => '',
'Acura' => 1334,
'Cadillac' => 511,
'Ford' => 5423,
);
$right = array(
'countZipRadius' => 0,
'zip' => 1,
'yearName' => 2,
'Acura' => 3,
'Cadilac' => 4,
'Ford' => 5,
'countTotal' => 6
);
//make sure both arrays are in the same order
ksort($original);
ksort($right);
array_multisort($right, $original);
print_r($original);
When you give it two arrays with the same number of elements it sorts both arrays, based on the order of the first array - in this case the 0, 1, 2, 3, etc. values in $right
Create a New Array (Array C)
Use a FOR loop to go through Array B
For each value in Array B, get the value with the same key from Array A and set Array C append those values to Array C. This will put them in the correct order in C.
Using scones' method:
$original = array(
'countTotal' => 7268,
'zip' => '',
'yearName' => '',
'countZipRadius' => '',
'Acura' => 1334,
'Cadillac' => 511,
'Ford' => 5423,
);
$right = array(
'countZipRadius' => 0,
'zip' => 1,
'yearName' => 2,
'Acura' => 3,
'Cadilac' => 4,
'Ford' => 5,
'countTotal' => 6
);
foreach ($right as $key => $value) {
$new[$key] = $original[$key];
}
print_r($new);
$array = array('a' => 100, 'b' => '5');
$newArray = array_combine(array_keys($array), range(0, count($array) - 1));
var_dump($newArray);