Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 8 years ago.
Improve this question
I have a multidimensional array that contains the data of locations, now I want to split this array into multiple arrays sorted by the postal code(postal code is an item in the location array)
I have:
array(
[0]=>array([name]=>"name1", [postalcode]=>"1111", [etc]=>"etc"),
[1]=>array([name]=>"name2", [postalcode]=>"2222", [etc]=>"etc")
);
And I want to push the first item to an array with the name 1111 and the other to 2222(and this for 10000+ locations in about 4000 postal code areas)
What about KISS?
Reference is used for performance on large iterations. READ MORE.
$input = array(
array('name' => "name1", 'postalcode' => "1111", 'etc' => "etc"),
array('name' => "name2", 'postalcode' => "2222", 'etc' => "etc"),
);
$result = array();
foreach ($input as &$array) {
$result[$array['postalcode']][] = $array;
}
First, this is not something you want to do on every request. Consider changing the data structure from wherever you are reading this information.
Second, as far as I can see you need to go through the array and build a new one:
$per_code = array();
for ($c=0; $c<count($codes); $c++)
$per_code[$codes[$c]['postalcode']] = $codes[$c];
If you want to reduce the memory impact, consider using the same instance from the original array.
$per_code = array();
for ($c=0; $c<count($codes); $c++)
$per_code[$codes[$c]['postalcode']] = &$codes[$c];
Say,
$location =array(
array('name'=>"name1", 'postalcode'=>"1111", 'etc'=>"etc"),
array('name'=>"name2", 'postalcode'=>"2222", 'etc'=>"etc")
);
$newAry = array();
foreach($location as $key=>$value)
{
$postcode = $value['postalcode'];
$newAry['location'][$postcode][] = $value;
}
print_r($newAry);
Related
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 2 years ago.
Improve this question
Need a sanity check on this one, I think I just confused myself. I am trying to loop throught the below array and get the fields back for multiple people that are register.
{
[12]=>
array(79) {
["Event Number"]=> int(466226)
["Event Info"]=> string(134) “Event ABC”
["Event Acct Code"]=> NULL
["email"] => string(12)"email#email.com
}
}
How can i best accomplish this?
This is what I tried
$associativeEventInfo=[];
foreach ($res as $eventInfo)
{
$associativeEventInfo[]=$eventInfo;
}
var dumping $associativeEventInfo returns the results
Id like to get each field out according to the array, for example
["EvenNumber"] =466226 so that I can then pass that over to database and do stuff.
So the goal is to remap the data to presumably database fields. First off, accessing the fields is quite easy:
// Assuming $returnedData is an array of assoc array containing the data;
foreach ($returnedData as $eventData)
{
$eventNumber = $eventData['Event Number'];
$eventInfo = $eventData['Event Info'];
// And so on
}
Remapping it is as simple as creating a new array with the correct format (one can also use array_map but I leave that as a readers exercise):
$remappedData = [];
// Assuming $returnedData is an array of assoc array containing the data;
foreach ($returnedData as $eventData)
{
$remappedData[] = [
'eventNumber' => $eventData['Event Number'],
'eventInfo' => $eventData['Event Info'],
// And so on
];
$eventNumber = $eventData['Event Number'];
$eventInfo = $eventData['Event Info'];
}
Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 4 years ago.
Improve this question
I wanted to output a 3 dimensional array that will come from the Database. This is my database looks like:
Basically, I wanted my first array will be the header_name and under the header_name the sub_header_name will come then underneath is the name
eg:
User Role Management => array(
'' => array (
'Create User Role'
)
),
Config Management => array(
'Organisation' => array('Create Country','Create
Organisation'),
'Site' => array('Create Site','Edit Site')
)
and here are my codes:
$getAllPermission = Permission::get();
$arrHeader = array();
$arrSubHeader = array();
$arrPermissions = array();
// $x = 0;
foreach($getAllPermission as $value){
$title = $value->header_name;
$sub_header_name = $value->sub_header_name;
$permission_name = $value->name;
if ($sub_header_name == ""){
$sub_header_name = 0;
}
array_push($arrPermissions,$permission_name);
$arrHeader[$title] = array($sub_header_name => array($arrPermissions));
//$x++;
}
and my output was like this:
You're pushing onto the same $arrPermissions array every time through the loop, that's why each of the roles gets a longer and longer copy of the permissions array.
You're overwriting $arrHeader[$title] each time through the loop instead of adding a new key to it.
Your desired output has a key of '' for the empty sub_header_name, so I don't see why you have the if that sets $sub_header_name = 0;.
It should simply be:
foreach ($getAllPermissions as $value) {
$arrHeader[$value->header_name][$value->sub_header_name][] = $value->name;
}
Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 5 years ago.
Improve this question
I have a code to modify the data that comes up from external API. However, I didn't like my code. I believe that there is a shorter way to do.
let me explain the flow:
I request to an api endpoint to get currency short codes. I mean $results contains these:
[0] => EURUSD
[1] => USDTRY
etc...
I want to save these as EUR, USD, TRY. I used str_split to do this. Also, I used array_unique to remove the same values.
Right now, my array contains this.
[0] => EUR
[3] => USD
[5] => TRY
It's not enough for me. I need to change keys according to my database structure.
My table contains: id, name, created
I have to rename each key as name. (btw I use Phnix to migrate and seeding)
$results = json_decode($httpResponse->getBody());
$data = [];
$prepared = [];
foreach ($results as $key => $item) {
$data = array_merge($data, str_split($item, 3));
}
$data = array_unique($data);
foreach ($data as $key => $item) {
array_push($prepared, ['name' => $item]);
}
$currency = $this->table('currency');
$currency->truncate();
$currency->insert($prepared)->save();
Do you have any clue for the best way?
in your code you make a lot of useless operation: considering that the lenght of the string is always 3 char you can simply use substr to obtain the currency code and use the currency code as key to make your array "unique" (if the same currency is added more than once, will "override" the previous one, whithout affecting the final result).
$results = json_decode($httpResponse->getBody());
$prepared = [];
foreach ($results as $item) {
$itemName = substr($item,0,3);
$prepared[$itemName] = ['name' => $itemName];
}
$currency = $this->table('currency');
$currency->truncate();
$currency->insert($prepared)->save();
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 5 years ago.
Improve this question
I have a complicated JSON and I need create array from this JSON.
I already parsed JSON and create a variablies like this:
$name = $json[response][docs][$i][name][0];
$osm_id = $json[response][docs][$i][osm_id][0];
$place = $json[response][docs][$i][place][0];
$population= $json[response][docs][$i][population][0];
now I need a array, with this variablies, where the $i is changing, like this:
$array = [array_1(name,osm_id,place,population),array_2(name_2,osm_id_2)]
Can you help me with the cycle to fill this array?
If my understanding is correct,
$expected_arr = array();
foreach($json[response][docs] as $inc => $values){
$data = array();
foreach($values as $key => $val){
$data[$key] = $val[0];
}
$expected_arr[$inc] = $data;
}
So you would get something like
array(0 => array( 'name'=>'xxx', 'osm_id'=>'yy',..), 1=> array('name'=>'',.. ,),...)
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 6 years ago.
Improve this question
The problem is to get the following result set:
'org1', 'unit1', 'proj1'
'org1', 'unit1', 'proj2'
'org1', 'unit2', 'proj1'
'org1', 'unit2', 'proj2'
'org2', 'unit1', 'proj1'
'org2', 'unit1', 'proj2'
to the following in php:
[{"units": [{"name": "unit1", "projects": ["project1", "project2"]}, {"name": "unit2", "projects": ["project1", "project2"]}], "name": "org1"}, {"units": [{"name": "unit1", "projects": ["project1", "project2"]}], "name": "org2"}]
Any suggestions?
You can use something like
$final_array = array();
foreach($array as $row){
$final_array[$row[0]][$row[1]][] = $row[2];
}
Now this will "convert the SQL result array into a multidimentional array/tree" but not like what you want yet.
So we shall have to process the array again..
$final_array_2 = array(); // Lets go deep
foreach ($final_array as $name => $units) {
$quarterfinal_array = array(); // Not deep enough
$semi_final_array = array();
foreach ($units as $proj_name => $projects) {
$nano_final_array = array(); // Lets dig deeper ;)
$nano_final_array['name'] = $proj_name;
$nano_final_array['projects'] = $projects;
$semi_final_array[] = $nano_final_array;
}
$quarterfinal_array['units'] = $semi_final_array;
$quarterfinal_array['name'] = $name;
$final_array_2[] = $quarterfinal_array;
}
echo json_encode($final_array_2);
PS: Sorry my choice of variable names are not the most ideal, but they get the work done ;) This is a P.O.C, You can always improve on it.
DEMO