I have the following situation and cannot find an easy way to do it.
I have 2 arrays:
1)
Array (
[0] => Array
(
[FirstName] => Tom
[LastName] => Siemens
[Id] => 10300
)
[1] => Array
(
[FirstName] => Sam
[LastName] => Tailor
[Id] => 10301
)
2)
Array
(
[0] => Array
(
[Type] => Invoice
[Number] => 6344394
[Project] => Array
(
[Name] => Test Project 1
[ResponsibleUserId] => 10300
[Id] => 498
[ResponsibleUser] =>
)
)
[1] => Array (
[Type] => Invoice
[Number] => 6345555
[Project] => Array
(
[Name] => Test Project 2
[ResponsibleUserId] => 10301
[Id] => 499
[ResponsibleUser] =>
)
)
What could be the best approach to get the "FirstName LastName" from the first array depends on the ID which must equal the Project Id from the second array and to put these values inside the second array -> Project -> ResponsibleUser?
The result I'm looking for is the following:
Final Array)
Array (
[0] => Array
(
[Type] => Invoice
[Number] => 6344394
[Project] => Array
(
[Name] => Test Project 1
[ResponsibleUserId] => 10300
[Id] => 498
[ResponsibleUser] => Tom Siemens
)
)
[1] => Array (
[Type] => Invoice
[Number] => 6345555
[Project] => Array
(
[Name] => Test Project 2
[ResponsibleUserId] => 10301
[Id] => 499
[ResponsibleUser] => Sam Tailor
)
)
If you start by indexing the first array by the id using array_column() ...
$idList = array_column($array1, null, "Id");
You can then just loop over the second array and pick out the name each time and update it...
foreach (array2 as &$project ) {
$id = $project["Project"]["ResponsibleUserId"];
$project["Project"]["ResponsibleUser"] = $idList[$id]["FirstName"]." ".$idList[$id]["LastName"];
}
Use &$project as this allow you to update the original value which is what your after.
Create a new array from array1 with the user id as the keys:
$newArray1 = array();
foreach($array1 as $values)
{
$newArray1[$values['Id']] = $values['FirstName']." ".$values['LastName'];
}
Then
foreach($array2 as $index => $val)
{
$array2[$index]['Project']['ResponsibleUser'] = $newArray1[$val['Project']['ResponsibleUserId'];
}
<?php
$names[0] = array("FirstName" => "Tom", "LastName" => "Siemens", "Id" => 10300);
$names[1] = array("FirstName" => "Sam", "LastName" => "Tailor", "Id" => 10301);
$projects[0] = array("Type" => "Invoice", "Number" => "6344394", "Project" => Array("Name" => "Test Project 1", "ResponsibleUserId" => 10300, "Id" => 498, "ResponsibleUser" => ""));
$projects[1] = array("Type" => "Invoice", "Number" => "6345555", "Project" => Array("Name" => "Test Project 2", "ResponsibleUserId" => 10301, "Id" => 499, "ResponsibleUser" => ""));
foreach ($projects as $pid => $project) {
foreach ($names as $nid => $name) {
if ($project["Project"]["ResponsibleUserId"] == $name["Id"]) {
$projects[$pid]["Project"]["ResponsibleUser"] = $name["FirstName"].' '.$name["LastName"];
};
};
};
print_r($projects);
?>
Related
I have this type array structure.
Array
(
[0] => Array
(
[name] => Name
[value] => Ram
)
[1] => Array
(
[name] => Gender
[value] => Male
)
[2] => Array
(
[name] => Age
[value] => 25
)
[3] => Array
(
[name] => Color
[value] => Red
)
[4] => Array
(
[name] => Color
[value] => Yellow
)
[5] => Array
(
[name] => Game
[value] => Cricket
)
[6] => Array
(
[name] => Game
[value] => Football
)
.
.
.
)
How can I find same names containing in whole array and combine their values? In above, Color and Game name is same, so I need Color and Game values in array instead. Note that there may be other names being similar not only Color and Game.
Array
(
[0] => Array
(
[name] => Name
[value] => Ram
)
[1] => Array
(
[name] => Gender
[value] => Male
)
[2] => Array
(
[name] => Age
[value] => 25
)
[3] => Array
(
[name] => Color
[value] => array( 'Red', 'Yellow' )
)
[4] => Array
(
[name] => Game
[value] => array( 'Cricket', 'Football' )
)
.
.
.
)
Try below code. And check if that helps you.
Note: For future ref when you ask a question here please provide the code you did so far. In this question it seems like you didn't try to solve it.
<?php
// example code
$newarray = [
[
"name" => "Name",
"value" => "Ram"
],
[
"name" => "Gender",
"value" => "Male"
],
[
"name" => "Age",
"value" => 25
],
[
"name" => "Color",
"value" => "Red"
],
[
"name" => "Color",
"value" => "Yellow"
],
];
//make an array of combined values using value of name as key of that array
$keyArray = [];
foreach($newarray as $k=>$v)
{
if(array_key_exists($v['name'],$keyArray))
{
$valueArray = [];
if(is_array($keyArray[$v['name']]))
{
$valueArray = $keyArray[$v['name']];
$valueArray[] = $v['value'];
$keyArray[$v['name']] = $valueArray;
}
else
{
$valueArray[] = $keyArray[$v['name']];
$valueArray[] = $v['value'];
$keyArray[$v['name']] = $valueArray;
}
}
else
{
$keyArray[$v['name']] = $v['value'];
}
}
//now loop through the key values and make key as name and value as value and push into a wrapper array
$finalArray = [];
foreach ($keyArray as $k=>$v)
{
$finalArray[] = [
"name"=>$k,
"value"=>$v
];
}
print_r($finalArray);
Recently I am working on a project that categorises 'Superheros' and 'Supervillains' based on their 'Franchaise' and origin of 'Superpower'. I want to fetch data from database as as Array #1 and displays them as Array #2 in php.
Array #1
Array
(
[0] => Array
(
[id] => 101
[Name] => Superman
[Franchise] => DC Comics
[Superpower] => Inherent
)
[1] => Array
(
[id] => 908
[Name] => Batman
[Franchise] => DC Comics
[Superpower] => Acquired
)
[2] => Array
(
[id] => 228
[Name] => Wolverine
[Franchise] => Marvel
[Superpower] => Acquired
)
[3] => Array
(
[id] => 158
[Name] => Iron Man
[Franchise] => Marvel
[Superpower] => Acquired
)
[4] => Array
(
[id] => 978
[Name] => Thor
[Franchise] => Marvel
[Superpower] => Inherent
)
)
Array #1 elements have to be grouped based on their 'Franchise' and count how many of them are 'Inherent' or 'Acquired' in terms of 'Superpower'.
Array #2
Array
(
[DC Comics] => Array
(
[Inherent] => 1
[Acquired] => 1
)
[Marvel] => Array
(
[Inherent] => 1
[Acquired] => 2
)
)
Here is your code without much logic,
foreach ($array1 as $val) {
if(!isset($array2[$val['Franchise']])) {
$array2[$val['Franchise']] = array('Inherent' => 0, 'Acquired' => 0);
}
$array2[$val['Franchise']][$val['Superpower']]++;
}
print_r($array2);
array_column() function to aggregate an inner key from a 2D array.
array_count_values() function counts all the values of an array.
Use this code snippet for count values:
$a = array ( array ("id" => "101", "Name" => "Superman", "Franchise" => "DC Comics", "Superpower" => "Inherent" ),
array ( "id" => "908", "Name" => "Batman", "Franchise" => "DC Comics", "Superpower" => "Acquired" ),
array ( "id" => "228", "Name" => "Wolverine", "Franchise" => "Marvel", "Superpower" => "Acquired" ),
array ( "id" => "158", "Name" => "Iron Man", "Franchise" => "Marvel", "Superpower" => "Acquired" ),
array ( "id" => "978", "Name" => "Thor", "Franchise" => "Marvel", "Superpower" => "Inherent" ));
echo "<pre>";
$return = array();
// first group array values by franchise
foreach($a as $val) {
if (!isset($return[$val['Franchise']])) {
$return[$val['Franchise']] = array();
}
$return[$val['Franchise']][] = $val;
}
$arr = array();
// count elements by key value pair in particular franchise
foreach ($return as $key => $value) {
$tmp = array_count_values(array_column($value, 'Superpower'));
$arr[$key] = $tmp;
}
print_r($arr);
Demo is here
With single and short array_reduce:
// $arr is your initial array
$result = array_reduce($arr, function($r, $v){
if (isset($r[$v["Franchise"]][$v["Superpower"]])) {
$r[$v["Franchise"]][$v["Superpower"]] += $r[$v["Franchise"]][$v["Superpower"]];
} else {
$r[$v["Franchise"]][$v["Superpower"]] = 1;
}
return $r;
}, []);
print_r($result);
The output:
Array
(
[DC Comics] => Array
(
[Inherent] => 1
[Acquired] => 1
)
[Marvel] => Array
(
[Acquired] => 2
[Inherent] => 1
)
)
This is my array structure:
Array
(
[0] => Array
(
[0] => Array
(
[topic_id] =>
[user_id] => ZGNjBQN9ac3K
[owner_id] => 15157
[tagged_field] => description
[created_date] => 2015-02-06 12:11:54
)
[1] => Array
(
[topic_id] =>
[user_id] => ZGNjAmD9ac3K
[owner_id] => 15157
[tagged_field] => description
[created_date] => 2015-02-06 12:11:54
)
)
)
I generate this structure before saving topics so i will get topic id only after this.
So in-order to save this array i need to set topic id to all index "topic_id"... lets say if topic_id is 11234 i need to updated all index with topic_id with value 11234.
Desired Output:
Array
(
[0] => Array
(
[0] => Array
(
[topic_id] => 11234
[user_id] => ZGNjBQN9ac3K
[owner_id] => 15157
[tagged_field] => description
[created_date] => 2015-02-06 12:11:54
)
[1] => Array
(
[topic_id] => 11234
[user_id] => ZGNjAmD9ac3K
[owner_id] => 15157
[tagged_field] => description
[created_date] => 2015-02-06 12:11:54
)
)
)
Try with -
$indexedArray = array();
foreach($yourArray as $value) {
foreach($value as $val) {
$indexedArray[$val['topic_id']][] = $val;
}
}
You need to use references in both foreach loops:
$arr = array(
array(
array("topic_id" => "", "user_id" => "ZGNjBQN9ac3K", "owner_id" => "15157", "tagged_field" => "description", "created_date" => "2015-02-06 12:11:54"),
array("topic_id" => "", "user_id" => "ZGNjBQN9ac3K", "owner_id" => "15157", "tagged_field" => "description", "created_date" => "2015-02-06 12:11:54"),
)
);
foreach($arr as &$value) {
foreach($value as &$val) {
$val['topic_id'] = $newvalue;
}
}
print_r($arr);
You can do by simple way using reference variable like
$yourArray = array(array(array("topic_id"=>"","user_id"=>110),array("topic_id"=>"","user_id"=>786)));
foreach($yourArray as &$value) {
foreach($value as &$val) {
$val['topic_id'] = "your_topic_id";
}
}
Output
Array
(
[0] => Array
(
[0] => Array
(
[topic_id] => your_topic_id
[user_id] => 110
)
[1] => Array
(
[topic_id] => your_topic_id
[user_id] => 786
)
)
)
so i retrieve a json, convert it into an array and i got this output:
Array
(
[Sid] => 23888555
[pages] => Array
(
[0] => Array
(
[id] => 13111071
[name] => Page 1
[slots] => Array
(
[0] => Array
(
[SlotId] => 6
[info] => Array
(
[id] => 5247
[color] => red
)
)
[1] => Array
(
[SlotId] => 4
[info] => Array
(
[id] => 5267
[color] => blue
)
)
[2] => Array
(
[SlotId] => 7
[info] => Array
(
[id] => 5267
[color] => green
)
)
)
)
[1] => Array
(
[id] => 13111072
[name] => Page 2
[slots] => Array
(
[0] => Array
(
[SlotId] => 6
[info] => Array
(
[id] => 5247
[color] => red
)
)
[1] => Array
(
[SlotId] => 4
[info] => Array
(
[id] => 5267
[color] => blue
)
)
)
)
)
)
I have no problem reading it whatsoever, what i wanna do is count for every page how many similar "last" id i got.
Exemple :
[pages][0][slots][0][info][id]
[pages][0][slots][1][info][id]
[pages][0][slots][3][info][id]
For the page 1, I wanna compare these 3 ids between them and count the occurrences.
[pages][1][slots][0][info][id]
[pages][1][slots][1][info][id]
For the page 2, I wanna compare these 2 ids between them and count the occurrences.
The output i want looks like this :
page 1 -> 1x5247
-> 2x5267
page 2 -> 1x5247
-> 1x5267
EDIT :
I tried using
foreach ($data['pages'] as $item) {
foreach ($item['slots'] as $slotnumber => $value) {
print_r(array_count_values($item['slots'][$slotnumber]['info']));
}
}
which returns me this :
Array ( [5247] => 1 [red] => 1 )
Array ( [5267] => 1 [blue] => 1 )
Array ( [5267] => 1 [green] => 1 )
So i think i might be able to use this but i don't know how.
I manually declared the array and then created the countstuff() function. This should work for you. I tested it and it work on my end. After going through all this trouble, I really do appreciated it if you choose my answer and up vote it.
<?php
$data = Array("Sid" => "23888555", "pages" => Array("0" => Array("id" => "13111071", "name" => "Page 1", "slots" => Array("0" => Array("SlotId" => "6", "info" => Array("id" => "5247", "color" => "red")), "1" => Array("SlotId" => "4", "info" => Array("id" => "5267", "color" => "blue")), "2" => Array("SlotId" => "7","info" => Array("id" => "5267", "color" => "green")))),
"1" => Array
(
"id" => "13111072",
"name" => "Page 2",
"slots" => Array
(
"0" => Array
(
"SlotId" => "6",
"info" => Array
(
"id" => "5247",
"color" => "red"
)
),
"1" => Array
(
"SlotId" => "4",
"info" => Array
(
"id" => "5267",
"color" => "blue"
)
)
)
)
)
);
//End of array declaration
//Now the really convoluted coding starts
//Create a function
function countstuff($yourarray){
foreach($yourarray as $mainarraykey => $mainarray){
if($mainarraykey == "pages"){
foreach($mainarray as $pageskey => $pagesarray){
//echo "Page \"$pageskey\"<br/>";
foreach($pagesarray as $pagessubarraykey => $pagessubarray_array){
if($pagessubarraykey == "slots"){
foreach($pagessubarray_array as $slotskey => $slots){
foreach($slots as $slotssubkey => $slotssub){
if($slotssubkey == "info"){
foreach($slotssub as $key => $value){
if($key == "id"){
//echo $value."<br/>";
$pages[$pageskey][] = $value;
}
}
}
}
}
}
}
}
}
}
return $pages;
}
//Execute the countstuff() function
$output = countstuff($data);
function showresults($input){
foreach($input as $pagekey => $page){
echo "Page $pagekey:<br/>";
$results = array_count_values($page);
foreach($results as $resultkey => $result){
echo $result."x".$resultkey."<br/>";
}
echo "<br/>";
}
}
showresults($output);
?>
I tried some things let me know what you guys think of this.
I get every id then enter them into an array then use array_count_values
$array_ids = array();
foreach ($data['pages'] as $item) {
$numberOfElements = count($item['slots']);
$z= 0;
foreach ($item['slots'] as $slotnumber => $value) {
$array_ids[$z] = $item['slots'][$slotnumber]['info']['id'];
// search for occurrences when the array is full
if (count($array_ids) == $numberOfElements) {
var_dump(array_count_values($array_ids));
// reset the array to 0 every time we loop through the whole infos
$array_ids = array();
}
$z++;
}
}
This seems to work for every page.
array (size=2)
5267 => int 2
5247 => int 1
array (size=2)
5267 => int 1
5247 => int 1
I need some clarity as to what PHP function can achieve what I'm aiming for.
This is a PHP array I have:
Array
(
[0] => Array
(
[id] => 6
[index] => 1
[active] => 1
[name] => MyName
)
[1] => Array
(
[id] => 1
[index] => 2
[active] => 1
[name] => YourName
)
[2] => Array
(
[id] => 2
[index] => 4
[active] => 1
[name] => TheirName
)
}
I want to take the "index" value and make it a KEY of that array parent, so the array would become this:
Array
(
[1] => Array
(
[id] => 6
[index] => 1
[active] => 1
[name] => MyName
)
[2] => Array
(
[id] => 1
[index] => 2
[active] => 1
[name] => YourName
)
[4] => Array
(
[id] => 2
[index] => 4
[active] => 1
[name] => TheirName
)
}
Can anyone please tell me how would I do this in PHP?
Thank you in advance.
you can use: array_column($array, null, 'index');
is the better solution, but only work for >= 5.5 php version
Not the most elegant solution, but it works (it doesn't actually move the array, it just generates a new one that corresponds to your requirements):
$resultArr = array();
foreach ($mainArr as $value) {
$resultArr[$value['index']] = $value;
}
unset($mainArr); // or $mainArr = $resultArr;
This way you won't overwrite any existing keys in your original array.
$a = array
(
0 => array
(
"id" => 6,
"index" => 1,
"active" => 1,
"name" => "MyName"
),
1 => Array
(
"id" => 1,
"index" => 2,
"active" => 1,
"name" => "YourName"
),
2 => Array
(
"id" => 2,
"index" => 4,
"active" => 1,
"name" => "TheirName"
)
);
$newArray = array();
foreach ($a as $foo) {
$newArray[$foo['index']] = $foo;
}
You have to do it manually with:
$input = array( /* your data */ );
$output = array();
foreach ( $input as $values ) {
$output[ $values['index'] ] = $values;
}
public static function normArray($key, $inputArray)
{
$outputArray = array();
foreach ($inputArray as $item) {
$index = intval($item[$key]);
$outputArray[$index] = $item;
}
return $outputArray;
}