Creating One Array from Another Array in PHP

How can I create an array from the values of another array's key?

Newer versions of PHP allow using array_map() with a function expression instead of a function name:

$arr2 = array_map(function($person) {
return $person['name'];
}, $arr1);

But if you are using a PHP < 5.3, it is much easier to use a simple loop, since array_map() would require to define a (probably global) function for this simple operation.

$arr2 = array();

foreach ($arr1 as $person) {
$arr2[] = $person['name'];
}

// $arr2 now contains all names

Creating one array from another array in php

foreach ($MainArray as $value) {
$name = $value['Machine_Name'];
unset($value['Machine_Name']);
$ConvertedArray[$name][] = $value;
}

Create an array from another arrays values

You can use array-reduce to aggregate the recruiter hours:

$lastMon = array(array("recruiter" => "AAA", "hours" => 4), array("recruiter" => "BBB", "hours" => 5), array("recruiter" => "AAA", "hours" => 3));

function reduceHours($carry, $item)
{
if (!array_key_exists($item["recruiter"], $carry))
$carry[$item["recruiter"]] = 0;
$carry[$item["recruiter"]] += $item["hours"];
return $carry;
}


$lastMonData = array_reduce($lastMon, "reduceHours", array());

This will output:

Array
(
[AAA] => 7
[BBB] => 5
)

Edited

Now that you added more data I can give you more detailed answer:

$str = '<xml><shifts><recruiter>John Smith</recruiter><hours>05</hours></shifts><shifts><recruiter>Mike Jones</recruiter><hours>04</hours></shifts><shifts><recruiter>John Smith</recruiter><hours>08</hours></shifts></xml>';
$arr = json_decode(json_encode((array) simplexml_load_string($str)), 1);

function sum($carry, $item) { return $carry + $item;}
function reduceHours($carry, $item)
{
if (!array_key_exists($item["recruiter"], $carry))
$carry[$item["recruiter"]] = 0;
$carry[$item["recruiter"]] += $item["hours"];
return $carry;
}

$lastMonData = array_reduce($arr["shifts"], "reduceHours", array());
$lastMonData["total"] = array_reduce($lastMonData, "sum");

Converting xml object to array is from here.

This will give output for $lastMonData:

Array
(
[John Smith] => 13
[Mike Jones] => 4
[total] => 17
)

I know the sum of total can be done in other ways but I tried to keep the example of using array_reduce.

Add one array elements into another array if value for a given key matches

First create a temp array to store index of a given id_modulo from first array. So while pushing an item from second array to first array, we don't have to search every time.

$arrModuleIndex     =   [];
// $arr here is your first array.
foreach($arr as $key => $data){
$arrModuleIndex[$data['id_modulo']] = $key;
}

Output:
Array
(
[114] => 0
[118] => 1
[128] => 2
)

Now loop through second array and push it to items of first array at index based on temporary array.

// Here $arr2 is your second array
foreach($arr2 as $data){
$arr[$arrModuleIndex[$data['id_modulo']]]['items'][] = $data;
}

Output:
Array
(
[0] => Array
(
[id_modulo] => 114
[nome_modulo] => 1. Acessos
[items] => Array
(
[0] => Array
(
[id_modulo] => 114
[id_pergunta] => 547
[pergunta] => Example
[resposta] => C
)

[1] => Array
(
[id_modulo] => 114
[id_pergunta] => 548
[pergunta] => Example
[resposta] => C
)

[2] => Array
(
[id_modulo] => 114
[id_pergunta] => 550
[pergunta] => Example
[resposta] => C
)

)

)

[1] => Array
(
[id_modulo] => 118
[nome_modulo] => 4. Área de Vivência
[items] => Array
(
[0] => Array
(
[id_modulo] => 118
[id_pergunta] => 549
[pergunta] => Example
[resposta] => C
)

)

)

[2] => Array
(
[id_modulo] => 128
[nome_modulo] => 14. Supressão
)

)

Pushing data into arrays stored in another array

Use reference on your foreach like so &$key to save your modification :

PHP make a copy of the variable in the foreach, so your $key is not actually the same as the one from your previous array.

From @Dharman :

& passes a value of the array as a reference and does not create a new
instance of the variable.

So just do :

$arr = array(array("blue"),array("green"));

foreach ($arr as &$value)
{
$value[]='yellow';
print_r($value);
}
foreach ($arr as $value)
{
print_r($value);
}

How do I add values from an array to another array with the same key?

This code will do what you want. It goes through all the entries of $arr2, looking for matching id values in $arr1 and, where it finds them, adding the email address from $arr2 to the list of emails in $arr1 for that id value:

foreach ($arr2 as $arr) {
if (($k = array_search($arr['id'], array_column($arr1, 'id'))) !== false) {
if (is_array($arr1[$k]['email'])) {
$arr1[$k]['email'][] = $arr['email'];
}
else {
$arr1[$k]['email'] = array($arr1[$k]['email'], $arr['email']);
}
}
}

Output:

Array (
[0] => Array (
[id] => 1
[name] => John
[email] => Array (
[0] => j@mail.com
[1] => john@yahoo.com
)
)
[1] => Array (
[id] => 2
[name] => Jane
[email] => Array (
[0] => jane@mail.com
[1] => jane@yahoo.com
[2] => jane.doe@hotmail.com
)
)
)

Laravel make array of another array objects

You're assigning $nums to be a new string on every iteration of the loop, rather than appending it to the array.

Just switch this line out:

$nums = $number['value'];

For

$nums[] = $number['value'];

Here are the docs for array_push(), which is the long way of writing the second line.

How to transfer one array to another array in php

Not sure what are you trying to achieve here...little more context would be helpful. But this is how you can do this,

$ages[] = array("Peter"=>22, "Clark"=>32, "John"=>28);

$ages1[] = array("demo"=>22);

$result[] = array_merge($ages[0],$ages1[0]);


Related Topics



Leave a reply



Submit