PHP String to array - Stuck with my string - php

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.

Related

Reorganise array, move indexes to specific locations php

I have an arbitrary number of arrays all containing the same format of data. There are 2 separate for loops looping through two separate SQL query results and adding them to 2 separate arrays.
Once I have all the information in both arrays, I am walking through them and joining them together to make a longer array.
However, as I am writing this array to a csv file, The information needs to be in order in the array so it writes it in order to the csv file. How can I do this?
Array 1
[1] => Array
(
[0] => 2017-07-21 00:00:00
[1] => Foo
[2] => Bar
[3] => 32.63
[4] => 18.36
[5] => 98.46
)
[2] => Array
(
[0] => 2017-07-21 00:00:00
[1] => Foo
[2] => Bar
[3] => 29.74
[4] => 148.68
[5] => 178.42
)
//etc
Array 2
[1] => Array
(
[0] => RTGH707321222
[1] => THIS
[2] => IS
[3] => TEXT
)
[2] => Array
(
[0] => RTGH707321220
[1] => SOME
[2] => WORDS
[3] => HERE
)
//etc
Joining the arrays together
array_walk($array2, function($values, $key) use (&$array1) {
$array1[$key] = array_merge($array1[$key], $values);
} );
After The array Merge - print_r($array1)
[1] => Array
(
[0] => 2017-07-21 00:00:00
[1] => Foo
[2] => Bar
[3] => 32.63
[4] => 18.36
[5] => 98.46
[6] => RTGH707321222
[7] => THIS
[8] => IS
[9] => TEXT
)
[2] => Array
(
[0] => 2017-07-21 00:00:00
[1] => Foo
[2] => Bar
[3] => 29.74
[4] => 148.68
[5] => 178.42
[6] => RTGH707321220
[7] => SOME
[8] => WORDS
[9] => HERE
)
//etc
So this is working fine. However, I would like to move some of these indexes around so that they are in a different order. I have looked into array_splice() but I am not sure if this is the correct method to use.
What I want it to look like
[1] => Array
(
[0] => 2017-07-21 00:00:00
[1] => RTGH707321222
[2] => TEXT
[3] => THIS
[4] => 18.36
[5] => 98.46
[6] => Foo
[7] => 32.63
[8] => IS
[9] => Bar
)
//etc
As you can see, all the information is still the same. The values have just been moved to different indexes. How can I sort the array so that it looks like the above. Can anyone point me in the right direction? Thanks.
This is a simpler method using array_replace() and an ordering array.
No extra loop, no temporary swapping variables.
Code: (Demo)
$array1=[
1=>['2017-07-21 00:00:00','Foo','Bar',32.63,18.36,98.46],
2=>['2017-07-21 00:00:00','Foo','Bar',29.74,148.68,178.42]
];
$array2=[
1=>['RTGH707321222','THIS','IS','TEXT'],
2=>['RTGH707321220','SOME','WORDS','HERE']
];
$order=[0=>'',6=>'',9=>'',7=>'',4=>'',5=>'',1=>'',3=>'',8=>'',2=>''];
array_walk($array2, function($values, $key) use (&$array1,$order) {
$array1[$key] = array_replace($order,array_merge($array1[$key], $values));
});
var_export($array1);
we can use swap technice here like,
<?php
foreach ($arr as $key => $value) {
$swap = $value[1];
$arr[$key][1] = $value[6];
$arr[$key][6] = $swap;
$swap = $value[9];
$arr[$key][9] = $value[2];
$arr[$key][2] = $swap;
$swap = $value[7];
$arr[$key][7] = $value[3];
$arr[$key][3] = $swap;
}
print_r($arr);
?>
$arr is your array.

break multidimensional array

I want to break down an multidimensional array into further single arrays.
Here is my array display..
Array
(
[family] => opensans
[variants] => Array
(
[0] => 300
[1] => 300italic
[2] => regular
[3] => italic
[4] => 600
[5] => 600italic
)
[subsets] => Array
(
[0] => cyrillic-ext
[1] => vietnamese
[2] => greek-ext
[3] => greek
[4] => cyrillic
[5] => latin-ext
[6] => latin
)
)
I want family/variants/subsets in different arrays so please help me.
Thanks in advance.
This sounds to simple but if that is your complete array all you need to do is
Assuming your big array is called $bigArray
$family = $bigArray['family'];
$variants = $bigArray['variants'];
$subsets = $bigArray['subsets'];
echo $family;
print_r($variants);
print_r($subsets);
$family of course will not be an array as $bigArray['family'] is not an array so $family will just be a string.
Try to use dynamic variables(php.net):
foreach ($array as $newVar => $newData) {
$$newVar = $newData;
}
var_dump($family);
var_dump($variants);
var_dump($subsets);
Let say that your array of
Array
(
[family] => opensans
[variants] => Array
(
[0] => 300
[1] => 300italic
[2] => regular
[3] => italic
[4] => 600
[5] => 600italic
)
[subsets] => Array
(
[0] => cyrillic-ext
[1] => vietnamese
[2] => greek-ext
[3] => greek
[4] => cyrillic
[5] => latin-ext
[6] => latin
)
)
is stored in a variable $myArr
You then need to do this.
foreach($myArr as $key => $value):
${key} = $value;
endforeach;
Should give you 3 arrays stored as $family, variants & subsets. Not sure about family, is that a string? in which case it will be string again unless you force it as a array.

remove spaces in a array php

for this array,
Array (
[0] => 'HOST:'
[1] => 'killbill'
[2] =>
[3] =>
[4] =>
[5] =>
[6] =>
[7] =>
[8] =>
[9] =>
[10] =>
[11] => 'Loss%'
[12] =>
[13] =>
[14] => 'Snt'
[15] =>
[16] =>
[17] => 'Last'
[18] =>
[19] =>
[20] =>'id'
)
it has empty values.by using this code it gives
foreach($array as $key => $subarray) {
$array[$key] = preg_grep('/^$/', $subarray, PREG_GREP_INVERT);
}
array (
[0] => HOST:
[1] => killbill
[11] => Loss%
[14] => Snt
[17] => Last
[20] =>id
)
that means it removes all the spaces. but it has the original key values .(compair above one and bellow one. then can get a clear idea what i'm saying).but i want to have it like this.
array (
[0] => 'HOST:'
[1] => 'killbill'
[2] => 'Loss%'
[3] => 'Snt'
[4] => 'Last'
[5] => 'id'
)
key values as 1,2,3,4.... so how could i get that.
simply use this instead of Foreach
array_values(array_filter($array));
that will remove the space and reorder your array.
look: http://codepad.org/howl3Opj
Just use array_filter().
$array = array_filter($array);
That will remove all the empty values -- ie blank, null, false, zero.
If you only want to remove values that are empty strings and keep other empty values (eg zero), you can specify the second parameter for array_filter(), which allows you to define a function to specify which elements should be filtered.
$array = array_filter($array, function($val) {return $val!=='';});
Hope that helps.
try this function it will help you to sort out the issue
$arr = array_map('array_values', $arr);
Use array_diff function
<?php
$array_space = array(0,3,4,45,12,"",54,23);
$remove = array("");
print_r(array_diff($array_space,$remove));
?>
See Output here
at start you need to take the array i gave him a name $arrWords
$arrWords = array_filter($arrWords, 'trim');
after i clean all the empty spaces i will make new array keys
$arrWords = array_values($arrWords);

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

array_push created array is acting strangely. When attempting to output associative array value returns first letter of Array or "A"

I am attempting to use a foreach to output the array below. I have created this array via array_push() based on preg_match if/else.
Array (
[0] => Array (
[date] =>
[clickurl] => some data
[url] => some data
[dispurl] => some Data...
[title] => Transformers: Revenge of the Fallen : Reviews
[abstract] => "Transformers: Revenge of the Fallen" is a horrible experience of unbearable length, briefly punctuated by three or four amusing moments.
)
[1] => Array (
[date] =>
[clickurl] => some data
[url] => some data
[dispurl] => some Data...
[title] => Transformers : Reviews
[abstract] => After a string of bad-to-mediocre films, director Michael Bay scores with blockbuster battling robots in "Transformers."
)
)
When attempting to output the array:
foreach ($reviewArr as $review) {
echo($review['clickurl']. '<br/><br/>');
}
The output is "A" which is the first letter of Array at the start of the array above. This is the same result as using $review[0];
When using:
foreach ($reviewArr as $review) {
echo($review. '<br/><br/>');
}
the output is:
Array (
[date] =>
[clickurl] => some data
[url] => some data
[dispurl] => some data...
[title] => Transformers : Reviews
[abstract] => After a string of bad-to-mediocre films, director Michael Bay scores with blockbuster battling robots in "Transformers."
)
I am not sure why this is happening. Any help will be greatly appreciated.
thanks!
UPDATE =
This is the original Array that I parse below to split into two different arrays.
Array
(
[bossresponse] => Array
(
[responsecode] => 200
[web] => Array
(
[start] => 0
[count] => 14
[totalresults] => 14
[results] => Array
(
[0] => Array
(
[date] =>
[clickurl] => http://url.com/1
[url] => http://url.com/1
[dispurl] => http://url.com/1...
[title] => Title of Content 1
[abstract] => This is the summary, This is the summary, This is the summary, ...
)
[1] => Array
(
[date] =>
[clickurl] => http://url.com/2
[url] => http://url.com/2
[dispurl] => http://url.com/2...
[title] => Title of Content 2
[abstract] => This is the summary, This is the summary, This is the summary, ...
)
)
)
)
)
This is how I am setting the $reviewArr[].
foreach ($results['bossresponse']['web']['results'] as $key => $result) {
$url = $result['clickurl'];
$title = $result['title'];
$abstract = $result['abstract'];
$resultItem = print_r($results['bossresponse']['web']['results'][$key], true);
if (preg_match ("/reviews/i", "$url")) {
array_push($reviewArr, "$resultItem");
} else {
array_push($resultsArr, "$resultItem");
}
}
UPDATE #2 -
I see thanks to #fabio that I am simply setting a string with $resultItem above. How can I achieve creating a multidimensional array? How can I build this as an array - all of my attempts returned errors, or a string.
Array
(
[0] => Array
(
[date] =>
[clickurl] => http://url.com/1
[url] => http://url.com/1
[dispurl] => http://url.com/1...
[title] => Title of Content 1
[abstract] => This is the summary, This is the summary, This is the summary, ...
)
[1] => Array
(
[date] =>
[clickurl] => http://url.com/2
[url] => http://url.com/2
[dispurl] => http://url.com/2...
[title] => Title of Content 2
[abstract] => This is the summary, This is the summary, This is the summary, ...
)
)
Change:
foreach ($results['bossresponse']['web']['results'] as $key => $result) {
$url = $result['clickurl'];
$title = $result['title'];
$abstract = $result['abstract'];
$resultItem = print_r($results['bossresponse']['web']['results'][$key], true);
if (preg_match ("/reviews/i", "$url")) {
array_push($reviewArr, "$resultItem");
} else {
array_push($resultsArr, "$resultItem");
}
}
to:
foreach ($results['bossresponse']['web']['results'] as $key => $result) {
if (preg_match ("/reviews/i", $result['clickurl'])) {
$reviewArr[] = $result;
} else {
$resultsArr[] = $result;
}
}
I don't know how you are pushing items on your array, but I think this could do the trick:
foreach ($reviewArr as $index=>$review) {
echo($review['clickurl']. '<br/><br/>');
}
For what weird reason are you filling the array with the return value of print_r???
// this will return a string
$resultItem = print_r($results['bossresponse']['web']['results'][$key], true);
So here is the reason of your behaviour: you're printing the first character of the print_r return value which is the string representation of $results[...][...] array.
Try it by yourself
$foo = "Hello world";
echo $foo[0]; // output H
P.S. echo($review. '<br/><br/>'); will output the whole string which is the print_r output.

Categories