php - shortcut for creating dynamic array with meaningful key names - php

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]));
}

Related

PHP String to array - Stuck with my string

This is my first question, i have been able to solve many issues by using your forum, but I am coming for your help because i do not know how to solve my issue.
I hope i will be understandable.
I want to convert a string to an array of array, but all my readings dit not help me to find a solution.
I have a string in this format
$string = "records[0].CardName=TEST records[0].CardNo=01234567 records[0].CreateTime=1566835406 records[0].Door=0 records[0].Method=1 records[0].Password= records[0].RecNo=1366 records[0].Status=1 records[0].URL= records[0].UserID=9901 records[1].CardName=TEST records[1].CardNo=01234567 records[1].CreateTime=1566851904 records[1].Door=0 records[1].Method=1 records[1].Password= records[1].RecNo=1368 records[1].Status=1 records[1].URL= records[1].UserID=9901";
So you can see that this is always the same structure and only values are modified, there is more than 2 repetition of this element, but to keep it readable i just put two of them.
I want to have an array created when the records[X] changes and then put each element matching records[X] into this array.
I want to convert it as an array which would look like this.
Array
(
[0] => Array
(
[CardName] =>TEST
[CardNo] => 01234567
[CreateTime] => 1566835406
[Door] => 0
[Method] => 1
[Password] =>
[RecNo] => 1366
[Status] => 1
)
[1] => Array
(
[CardName] => TEST
[CardNo] => 01234567
[CreateTime] => 1566835406
[Door] => 0
[Method] => 1
[Password] =>
[RecNo] => 1366
[Status] => 1
)
)
The goal is to access the last element of the array and to be precise the value CreateTime like this : end($array)['CreateTime'].
What I have try does not help me and i am stuck with no idea on how to deal with that issue.
$array = preg_split('/\s+/',$string);
if(is_array($array) {
print_r($array);
}
// Gives me this :
Array
(
[0] => records[0].CardName=TEST
[1] => records[0].CardNo=01234567
[2] => records[0].CreateTime=1566835406
[3] => records[0].Door=0
[4] => records[0].Method=1
[5] => records[0].Password=
[6] => records[0].RecNo=1366
[7] => records[0].Status=1
[8] => records[1].CardName=TEST
[9] => records[1].CardNo=01234567
[10] => records[1].CreateTime=1566835508
[11] => records[2].Door=0
[12] => records[3].Method=1
[13] => records[4].Password=
[14] => records[5].RecNo=1366
[15] => records[6].Status=1
)
I have also tried something like that with multiple different delimiter with no success
function multiexplode ($delimiters,$string) {
$ary = explode($delimiters[0],$string);
array_shift($delimiters);
if($delimiters != NULL) {
foreach($ary as $key => $val) {
$ary[$key] = multiexplode($delimiters, $val);
}
}
return $ary;
}
// Example of use
$string = "records[0].CardName=APKO records[0].CardNo=88043527 records[0].CreateTime=1566835406 records[0].Door=0 records[0].Method=1 records[0].Password= records[0].RecNo=1366 records[0].Status=1 records[0].URL= records[0].UserID=9901 records[1].CardName=APKO records[1].CardNo=88043527 records[1].CreateTime=1566851904 records[1].Door=0 records[1].Method=1 records[1].Password= records[1].RecNo=1368 records[1].Status=1 records[1].URL= records[1].UserID=9901";
$delimiters = Array('/\s+/',".",'=');
$res = multiexplode($delimiters,$string);
print_r($res);
Thanks for your help. I hope there is something that can be done to achieve this.
TaG
This goes along the lines of splitting the text at multiple parts with explode(). Starting using records[ as the delimiter so that this should mean even values with spaces are maintained. Then breaking the key down into the individual components...
$parts = explode("records[", $string);
// Remove empty item of start
array_shift($parts);
$output = [];
foreach ( $parts as $part ) {
list($key, $value) = explode("=", $part, 2);
list($id, $field) = explode("].", $key);
$output[$id][$field] = rtrim($value);
}
print_r($output);
gives...
Array
(
[0] => Array
(
[CardName] => TEST
[CardNo] => 01234567
[CreateTime] => 1566835406
[Door] => 0
[Method] => 1
[Password] =>
[RecNo] => 1366
[Status] => 1
[URL] =>
[UserID] => 9901
)
[1] => Array
(
[CardName] => TEST
[CardNo] => 01234567
[CreateTime] => 1566851904
[Door] => 0
[Method] => 1
[Password] =>
[RecNo] => 1368
[Status] => 1
[URL] =>
[UserID] => 9901
)
)
If there are no spaces other than the delimiter, you can replace a few things and get a valid query string. The replacements will give you a query string similar to this:
records[0]["CardName"]=TEST&records[0]["CardNo"]=01234567
That can be parsed into an array:
parse_str(str_replace([' ','.','='], ['&','["','"]='], $string), $result);
If there are other spaces then even some fancy regex will fail, as there is no way to tell what is a delimiter and what is not.

Access several arrays and change their keys

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

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;
}

How to prevent declaring an associative key while hardcoding array data?

Not sure if I can word this properly but I need to create and array with some array of other information. Right now it spits out like this:
And my code goes like this:
$calNames = array(
'affordability',
'balloon-payment',
'budget',
'early-payoff',
'fuel-savings',
'lease-vs-finance',
'monthly-payment' => array( 'name' => 'test3' ),
'refinance',
'single-pay-lease',
);
print_r( $calNames );
I want it to create the array like this:
Array
(
[0] => affordability
[1] => monthly-payment
[2] => budget
[3] => early-payoff
[4] => fuel-savings
[5] => lease-vs-finance
[6] => monthly-payment => Array
(
[name] => test3
)
[7] => refinance
[8] => single-pay-lease
)
Strange way to do it, but this matches your result as close as possible:
$calNames = array(
'affordability',
'balloon-payment',
'budget',
'early-payoff',
'fuel-savings',
'lease-vs-finance',
array('monthly-payment' => array( 'name' => 'test3' )),
'refinance',
'single-pay-lease',
);
Array
(
[0] => affordability
[1] => balloon-payment
[2] => budget
[3] => early-payoff
[4] => fuel-savings
[5] => lease-vs-finance
[6] => Array
(
[monthly-payment] => Array
(
[name] => test3
)
)
[7] => refinance
[8] => single-pay-lease
)

How to echo an array value

I am fairly new to PHP and I am writing a PHP function that grabs an object from SOAP.
I found a code to convert it to an array but I can't manage to echo any data.
The array from print_r
Array
(
[Status] => Array
(
[Code] => 0
[Message] => OK
)
[Order] => Array
(
[OrderNumber] => 9334543
[ExternalOrderNumber] =>
[OrderTime] => 2014-07-15T15:20:31+02:00
[PaymentMethod] => invoice
[PaymentStatus] => Paid
[ShipmentMethod] => Mypack
[DeliveryStatus] => Delivered
[Language] => sv
[Customer] => Array
(
[CustomerId] => 13556
[CustomerNumber] =>
[Username] => admin
[Approved] => 1
[OrgNumber] => 9309138445
[Company] =>
[VatNumber] =>
[FirstName] => Jane
[LastName] => Doe
[Address] => Gatan
[Address2] =>
[Zip] => 1230
[City] => Staden
[Country] => Sweden
[CountryCode] => SE
[PhoneDay] => 84848474
[PhoneNight] =>
[PhoneMobile] =>
[Email] => mail#msn.com
[NewsLetter] =>
[OrgType] => person
[OtherDelivAddress] =>
[DelivName] =>
[DelivAddress] =>
[DelivAddress2] =>
[DelivZip] =>
[DelivCity] =>
[DelivCountry] =>
[DelivCountryCode] =>
)
[Comment] =>
[Notes] => 9063025471 UK/MA
[CurrencyCode] => SEK
[ExchangeRate] => 1
[LanguagePath] => se
[FreightWithoutVat] => 0
[FreightWithVat] => 0
[FreightVatPercentage] => 25
[PayoptionFeeWithoutVat] => 0
[PayoptionFeeWithVat] => 0
[PayoptionFeeVatPercentage] => 25
[CodWithoutVat] => 0
[CodWithVat] => 0
[CodVatPercentage] => 0
[DiscountWithoutVat] => 0
[DiscountWithVat] => 0
[DiscountVat] => 0
[TotalWithoutVat] => 4388
[TotalWithVat] => 5485
[TotalVat] => 1097
[PayWithoutVat] =>
[AffiliateCode] =>
[AffiliateName] =>
[OrderField] => Array
(
[0] => Array
(
[Name] => external_ref
[Value] => 43445
)
[1] => Array
(
[Name] => webshopid
[Value] => 423
)
[2] => Array
(
[Name] => webshopname
[Value] => Manuell
)
)
)
)
Non working code
echo $array[1][0]
I have tried different combos of indexes. I know how to return the values from the soap object but if I could do it this way it would be easier. It should work shouldn't it?
$array[1] is the second index of the array. the key of this array us "Status", this array contains a code and message
i assume you want to echo the message, you can do that with the following
echo $array[1]["Status"]["Message"];
You should use $array['Status']['Code'] , $array['Status']['Message'], $array['Order']['OrderNumber'], $array['Order']['Customer']['CustomerId'] and so on to display your data. It's an associative array so you need to use string keys and not numbers
try
$array['Order']['Customer']['LastName']
is my best guess without losing my sanity in that one line.
But for us to be sure please post the print_r($array) output
There are some way I always do this:
print_r($array);
And the other way is
$array[0]['Order']['LastName']
Try to access the arrays elements with the string keys, not the integer ones you are using:
echo $array['Order']['Customer']['Address'];
Another way you could see what is going on is by iterating through the array, and print out the keys and values:
foreach ($array as $key => $value)
echo "Key=$key value=$value<br>";

Categories