Access several arrays and change their keys - php

I have got several or an amount of arrays which cannot be foreseen.
I want to access them und change their keys. I guess with a loop.
Array
(
[count] => 1
[0] => Max, Mustermann
[1] => Job
[2] => Companyname
[3] => IT
[4] => CEO
[5] => N610-611
[6] => +49 (30) 111111
[7] => +49 (30) 111111
[8] => max#company.de
)
Array
(
[count] => 1
[0] => Alicia Keys
[1] => Job
[2] => Companyname
[3] => IT
[4] => CEO
[5] => N610-N611
[6] => +49 11111
[7] => +49 11111
[8] => alikey#company.de
)
I'd like to have an output like this:
Array
(
[count] => 1
[Name] => Max, Mustermann
[Jobname] => Job
[Company] => Companyname
[Division] => IT
[CEO] => CEO
[Room] => N610-611
[Tel] => +49 (30) 111111
[Fax] => +49 (30) 111111
[E-Mail] => max#company.de
)
Array
(
[count] => 1
[Name] => Alicia Keys
[Job] => Job
[Company] => Companyname
[Division] => IT
[CEO] => CEO
[Room] => N610-N611
[Tel] => +49 11111
[Fax] => +49 11111
[E-Mail] => alikey#company.de
)
I'm not sure whether to use a foreach oder a for loop, or if a loop is even necessary. I know that changing keys is not that simple and read of a second array which holds the keys you want to change to. But I'm not sure how to do that

You can use array_combine() along with foreach() with predefined keys arrays
//predefined keys array
$index_array = array('count','Name','Jobname','Company','Division','CEO','Room','Tel','Fax','E-Mail');
foreach($array as &$value){
$value = array_combine($index_array ,$value);
}
Output:-https://3v4l.org/VnmWJ
Note:- If your array is single-dimensional then:
$array = array_combine($index_array ,$array);
Output:-https://3v4l.org/R8oY0
Explanation:-
foreach() because it take care about indexes as well as more readable. (save you from undefined index error happen multiple times using for() loop)
&$valueis passing by reference, so that any change in child array will reflect in the original/initial array automatically.

If you have a 1D array and you want to change keys of this array. It's enough to define an array with new keys and change keys of array in a loop. I make a example in following snippets code:
<?php $arr = [
'count' => 1,
'0' => 'Max Mustermann',
'1' => 'Job',
'2' => 'Companyname',
'3' => 'IT',
'4' => 'CEO',
'5' => 'N610-611',
'6' => '+49 (30) 111111',
'7' => '+49 (30) 111111',
'8' => 'max#company.de',
];
$arr2 = ['count', 'Name', 'Jobname', 'Company', 'Division', 'CEO', 'Room', 'Tel', 'Fax', 'E-Mail'];
$index = 0;
foreach($arr as $oldkey => $value) {
$arr[$arr2[$index]] = $arr[$oldkey];
unset($arr[$oldkey]);
$index++;
}
print_r($arr);
you can see output in this link

Related

how to remove array value from array when value not same from both the value [duplicate]

This question already has answers here:
How to Remove value from an array using another array with multiple values?
(4 answers)
Closed 4 years ago.
I have two array, and i want to remove duplicate record from array2. i don't want to link_id 35 record in array 2 because link_id 35 record is present in array1 so it's not show in array2.
I tried with array_map and Unique methods but it's not working well because i think both the array doesn't have the same value.
$array1=
[0] => stdClass Object
(
[link_id] => 35
[link_name] => Test Listerine cool mint packets 3 pack
[alias] => aa
[link_desc] =>
[user_id] => 47
[link_hits] => 103
[link_votes] => 1
[link_rating] => 5.000000
[link_featured] => 0
[link_published] => 1
[link_approved] => 1
[link_template] =>
)
[1] => stdClass Object
(
[link_id] => 373
[link_name] => Test Subject Data Collection Fish Fresh Yellow Tail
[alias] => ba
[link_desc] =>
[user_id] => 47
[link_hits] => 198
[link_votes] => 8
[link_rating] => 2.875000
[link_featured] => 0
[link_published] => 1
[link_approved] => 1
[link_template] =>
)
$array2 =
[0] => stdClass Object
(
[link_id] => 35
[link_name] => Test Listerine cool mint packets 3 pack
[link_desc] =>
[lat] => 0.000000
[lng] => 0.000000
[contactperson] =>
[cat_name] => AA - Made in USA
[link_votes] => 1
[link_rating] => 5.000000
[link_featured] => 0
[value] => 30020864
)
[1] => stdClass Object
(
[link_id] => 541
[link_name] => Test Subject Data Collection Fish Fresh Yellow Tail
[link_desc] =>
[lat] => 25.182573
[lng] => -80.093079
[country] => United States
[postcode] => 33431
[contactperson] => Captain Jack Certified Charters
[cat_name] => BA - Product of USA
[link_votes] => 8
[link_rating] => 2.875000
[link_featured] => 0
[value] => NA
)
You can do that with array-filter. First extract all the ids from the first array and then filter the second array based of those ids.
$arr1 = array( (object) ["link_id"=> 35, "key" => "AAA"], (object) ["link_id"=> 373, "key" => "BBB"]);
$arr2 = array( (object) ["link_id"=> 35, "key" => "CCC"], (object) ["link_id"=> 341, "key" => "DDD"]);
$ids = array_column($arr1, "link_id");
$arr2 = array_filter($arr2, function ($e) use ($ids) {
return !in_array($e->link_id, $ids); //keep him in arr2 only if NOT in ids of arr1
});
Updated more fast answer Consider big amount of data (as for #mickmackusa comment) use this:
$ids = [];
foreach($arr1 as $e)
$ids[$e->link_id] = true;
$arr2 = array_filter($arr2, function ($e) use ($ids) {
return !isset($ids[$e->link_id]);
});
First solution is in O(n^2) and the second is in O(n)
This should do in php7.
Untested code:
var_export(array_diff_key(array_column($array2, null, 'link_id'), array_column($array1, null, 'link_id'));
Assign new 1st level keys to both arrays, then filter on those keys.
Checking against keys will be more efficient than making iterated calls of in_array.

Extract data from Array/Object in PHP?

First off, I'm new to PHP and coding in general, so this might be quite an obvious answer.
I'm currently working with the Strava API, and I'm trying to extract data from an Array/Object which is the result of the following API call:
$recentactivities = $api->get('athlete/activities', array('per_page' => 100));
which returns:
Array (
[1] => stdClass Object (
[id] => XXXX
[resource_state] => 2
[external_id] => XXXX
[upload_id] => XXXX
[athlete] => stdClass Object (
[id] => XXXX
[resource_state] => 1
)
[name] => Let\'s see if I can remember how to do this cycling malarkey...
[distance] => 11858.3
[moving_time] => 1812
[elapsed_time] => 2220
[total_elevation_gain] => 44
[type] => Ride
[start_date] => 2014-07-12T13:48:17Z
[start_date_local] => 2014-07-12T14:48:17Z
[timezone] => (
GMT+00:00
) Europe/London
[start_latlng] => Array (
[0] => XXXX
[1] => XXXX
)
[end_latlng] => Array (
[0] => XXXX
[1] => -XXXX
)
[location_city] => XXXX
[location_state] => England
[location_country] => United Kingdom
[start_latitude] => XXXX
[start_longitude] => XXXXX
[achievement_count] => 4
[kudos_count] => 1
[comment_count] => 0
[athlete_count] => 1
[photo_count] => 0
[map] => stdClass Object (
[id] => a164894160
[summary_polyline] => XXXX
[resource_state] => 2
)
[trainer] =>
[commute] =>
[manual] =>
[private] =>
[flagged] =>
[gear_id] => b739244
[average_speed] => 6.544
[max_speed] => 10.8
[average_cadence] => 55.2
[average_temp] => 29
[average_watts] => 99.3
[kilojoules] => 179.9
[device_watts] =>
[average_heartrate] => 191.2
[max_heartrate] => 200
[truncated] =>
[has_kudoed] =>
)
This repeats for the most recent activities.
I'm attempting to extract average_heartrate, which I can do for a single object using the following:
$recentactivities[1]->average_heartrate;
but I'd like to extract all instances of average_heartrate from the Array. I've tried to use a foreach statement, but to be honest, I have no idea where to start.
Any help would be much appreciated.
It's actually pretty simple you can indeed use a foreach loop:
foreach($myArray as $obj){
//$obj is an object so:
if(isset($obj->average_heartrate)){
echo $obj->average_heartrate;
}
}
With this code you iterate through your array with objects and save the wanted array within an array so you can work further with it.
$heartrateArray = array(); // create a new array
//iterate through it with an foreach
foreach($recentactivities as $activity){
// save the average_heartrate as a value under a new key in the array
$heartrateArray[] = $activity->average_heartrate;
}

Get keys of 5 bigests value from array

I have one problem. I must get 5 images which rates are the biggest. I have table which key = image_id and value = average rating.
Below is print_r of this array
Array ( ['5'] => 5.00 ['4'] => 3.05 ['12'] => 3.00 ['11'] => 4.00 ['21'] => 2.11 ['53'] => 4.44 )
For example
['5'] => 5.00
means that img which id = '5' have rating 5.00
Expected output 2 Arrays ($id and $rating)
Array ( [0] => '5' [1] => '53' [2] => '11' [3] => '4' [4] => '12' )
Array ( [0] => '5.00' [1] => '4.44' [2] => '4.00' [3] => '3.05' [4] => '3.00' )
Can you help me in this?
Use arsort(); and array_slice();
You can also avoid making 2 separate arrays with functions like array_keys(); and array_values();
// Original array
$array = array(
5 => 5.00,
4 => 3.05,
12 => 3.00,
11 => 4.00,
21 => 2.11,
53 => 4.44
);
// Sort array & maintain keys
arsort($array);
// Now get the first 5 elements, keeping the keys
$array = array_slice($array, 0, 5, true);
// IDs
print_r(array_keys($array));
// Ratings
print_r(array_values($array));
Have you tried to use arsort or uasort?

How To push array elements from one array to another array

Hello people here is the code that i was using initially....
array_push($Parameter_IdArray, $Parameter_Id1, $Parameter_Id2, $Parameter_Id3, $OptParameter_Id);
array_push($Eqt_ParamArray, $eqt_param1, $eqt_param2, $eqt_param3, $Opt_eqt_param1);
i had no issues to push array values .... but now $eqt_param1, $eqt_param2, $eqt_param3 and $Opt_eqt_param1 are in one more array it is something like this
Array ( [Profile_Id] => 4 [eqt_param] => Array ( [0] => 4.00 [1] => 4.00 [2] => 4.00 ) [Parameter_Id1] => 8 [min_param] => Array ( [0] => 1.00 [1] => 1.00 [2] => 1.00 ) [max_param] => Array ( [0] => 5.00 [1] => 5.00 [2] => 5.00 ) [Wtg_param] => Array ( [0] => 25.00 [1] => 25.00 [2] => 50.00 ) [Parameter_Id2] => 5 [Parameter_Id3] => 1 [Opt_eqt_param] => Array ( [0] => 0.00 ) [OptParameter_Id] => 14 [Opt_wtg] => Array ( [0] => 1.05 ) [operator] => Array ( [0] => M ) [eqt_pay] => 1,574,235 [rec_sal] => 1,485,000 [#] => -6.01 % [Emp_Id] => 490699 [Emp_Process] => Confirm New Pay )
now i need tp push array values $eqt_param1, $eqt_param2, $eqt_param3 and $Opt_eqt_param1 to $Eqt_ParamArray how to do that?
If I understand correctly, you've now got an associative array in PHP. On that assumption, I went ahead and reformatted the nightmare for you:
$myarray = array(
"Profile_Id" => 4,
"eqt_param" => array(4.00, 4.00, 4.00),
"Parameter_Id1" => 8,
"min_param" => array (1.00, 1.00, 1.00 ),
"max_param" => array (5.00, 5.00, 5.00 ),
"Wtg_param" => array (25.00, 25.00, 50.00 ),
"Parameter_Id2" => 5,
"Parameter_Id3" => 1,
"Opt_eqt_param" => array (0.00),
"OptParameter_Id" => 14,
"Opt_wtg" => array (1.05),
"operator" => array ("M"),
"eqt_pay" => array(1,574,235),
"rec_sal" => array(1,485,000),
"#" => "-6.01 %",
"Emp_Id" => 490699,
"Emp_Process" => "Confirm New Pay"
);
What this good formatting now makes clear is that you can use array_push directly on the "eqt_param" index:
array_push($myArray["eqt_param"], $eqt_param1, $eqt_param2, $eqt_param3, $Opt_eqt_param1);
You may also mean that you want to replace it, which is easy too:
$myArray['eqt_param'] = array($eqt_param1, $eqt_param2, $eqt_param3, $Opt_eqt_param1);
The same principles apply in Javascript, which you have had tagged so maybe you mean that.

php - shortcut for creating dynamic array with meaningful key names

I have some logic that builds a multi-dimensional array based on matches found in a regex. I call the explode function,using a delimiter.
Everything works and my array looks like this:
Array (
[0] =>
Array (
[0] => A1
[1] => 100/1000T
[2] => No
[3] => Yes
[4] => Down
[5] => 1000FDx
[6] => Auto
[7] => off
[8] => 0
)
[1] => Array (
[0] => A2
[1] => 100/1000T
[2] => No
[3] => Yes
[4] => Down
[5] => 1000FDx
[6] => Auto
[7] => off
[8] => 0
) etc.etc...
In order to keep the code in the front end "dumb", i want to change the keys from numbers to strings that represent what the values are. These strings will be used as column headings in a table. So for example:
Array (
[0] =>
Array (
[port] => A1
[Type] => 100/1000T
[Alert] => No
[Enabled] => Yes
[Status] => Down
[Mode] => 1000FDx
[MDIMode] => Auto
[FlowCtrl] => off
[BcastLimit] => 0
)
[1] => Array (
[port] => A2
[Type] => 100/1000T
[Alert] => No
[Enabled] => Yes
[Status] => Down
[Mode] => 1000FDx
[MDIMode] => Auto
[FlowCtrl] => off
[BcastLimit] => 0
) etc.etc...
Here's the code that generates this array:
$portdetailsArray = array();
foreach ($data as $portdetails) {
$pattern = '/(\s+)([0-9a-z]*)(\s+)(100\/1000T|10|\s+)(\s*)(\|)(\s+)(\w+)(\s+)(\w+)(\s+)(\w+)(\s+)(1000FDx|\s+)(\s*)(\w+)(\s*)(\w+|\s+)(\s*)(0)/i';
if (preg_match($pattern, $portdetails, $matches)) {
$replacement = '$2~$4~$8~$10~$12~$14~$16~$18~$20';
$portdetails= preg_replace($pattern, $replacement, $portdetails);
array_push($portdetailsArray, explode('~',$portdetails));
}
}
I guess instead of using the explode function, I can manually loop through my string. Each time I find a "~", i know it's the start of a new field so i can add they key /value pair manually.
But I was just wondering if anyone had ideas on other ways to do this.
Thanks.
To reply to your original question, you could use the array_combine function, to replace the keys.
$row = explode('~',$portdetails);
$row = array_combine(array(
'port',
'Type',
'Alert',
'Enabled',
'Status',
'Mode',
'MDIMode',
'FlowCtrl',
'BcastLimit'), $row);
But even better, you should use the clearer (verbose is clearer in this case)
if (preg_match($pattern, $portdetails, $matches)) {
array_push($portdetailsArray, array(
'port' => $matches[2],
'Type' => $matches[4],
'Alert' => $matches[8],
'Enabled' => $matches[10],
'Status' => $matches[12],
'Mode' => $matches[14],
'MDIMode' => $matches[16],
'FlowCtrl' => $matches[18],
'BcastLimit' => $matches[20]));
}

Categories