I am new PHP question and I am trying to create an array from the following string of data I have. I haven't been able to get anything to work yet. Does anyone have any suggestions?
my string:
Acct_Status=active,signup_date=2010-12-27,acct_type=GOLD,profile_range=31-35
I want to dynamically create an array called "My_Data" and have id display something like my following, keeping in mind that my array could return more or less data at different times.
My_Data
(
[Acct_Status] => active
[signup_date] => 2010-12-27
[acct_type] => GOLD
[profile_range] => 31-35
)
First time working with PHP, would anyone have any suggestions on what I need to do or have a simple solution? I have tried using an explode, doing a for each loop, but either I am way off on the way that I need to do it or I am missing something. I am getting something more along the lines of the below result.
Array ( [0] => Acct_Status=active [1] => signup_date=2010-12-27 [2] => acct_type=GOLD [3] => profile_range=31-35} )
You would need to explode() the string on , and then in a foreach loop, explode() again on the = and assign each to the output array.
$string = "Acct_Status=active,signup_date=2010-12-27,acct_type=GOLD,profile_range=31-35";
// Array to hold the final product
$output = array();
// Split the key/value pairs on the commas
$outer = explode(",", $string);
// Loop over them
foreach ($outer as $inner) {
// And split each of the key/value on the =
// I'm partial to doing multi-assignment with list() in situations like this
// but you could also assign this to an array and access as $arr[0], $arr[1]
// for the key/value respectively.
list($key, $value) = explode("=", $inner);
// Then assign it to the $output by $key
$output[$key] = $value;
}
var_dump($output);
array(4) {
["Acct_Status"]=>
string(6) "active"
["signup_date"]=>
string(10) "2010-12-27"
["acct_type"]=>
string(4) "GOLD"
["profile_range"]=>
string(5) "31-35"
}
The lazy option would be using parse_str after converting , into & using strtr:
$str = strtr($str, ",", "&");
parse_str($str, $array);
I would totally use a regex here however, to assert the structure a bit more:
preg_match_all("/(\w+)=([\w-]+)/", $str, $matches);
$array = array_combine($matches[1], $matches[2]);
Which would skip any attributes that aren't made up of letters, numbers or hypens. (The question being if that's a viable constraint for your input of course.)
$myString = 'Acct_Status=active,signup_date=2010-12-27,acct_type=GOLD,profile_range=31-35';
parse_str(str_replace(',', '&', $myString), $myArray);
var_dump($myArray);
Related
I want to Remove all the Elements from my array which is after , but I am unable to do this.
I have an array like this => ["18-08-2022, 05:08:23pm","18-08-2022, 05:09:05pm"]
and I want to print array something like this => ["18-08-2022","18-08-2022"]
I want to remove Elements after the ,
This is what I tried
<?php
while ($row = mysqli_fetch_array($result)) {
$Etime[] = $row["Etime"];
$Etime1[]=$row["Etime"];
$E2[]=substr($Etime1[],',',true);
}
$Etime = json_encode($Etime);
$Etime1=json_encode($Etime1);
echo $Etime1
?>
this is easy-
steps to do so-
1.Parse your array as string.
2.store that in a variable.
3. then use a if loop and use php explode funtion. explode function will seperate that string elements by the seperator in this case the "," you want to remove.
explode(string $separator, string $string)
where,
separator-The boundary string.
string-The input string.
limit
example=
$text = "hello,there";
//using explode-
var_dump( explode( ',', $input2 ) );
output=
array(2)
(
[0] => string(5) "hello"
[1] => string(5) "there"
)
more about explode() here- https://www.php.net/manual/en/function.explode.php
Here's a simple php that generates the output you want. Since you only need date bits I have provided you with only the date bits. You can get general idea from here
$arr = ["18-08-2022, 05:08:23pm","18-08-2022, 05:09:05pm"];
//
// sample output: [ "18-08-2022", "18-08-2022" ]
//
$dateMappedToYourFormat = array_map(function($dt) {
return explode(",", $dt)[0]; // getting everything before comma
}, $arr);
echo implode(",", $dateMappedToYourFormat); //to view your result
I have an array with some keys and I want to get the array values according to the array keys where the keys are in a string.
Example:
$arr = array(
"COV" => "Comilla Victorians",
"RK" => "Rajshaji Kings"
);
$str = "COV-RK";
Now I want to show Comilla Victorians VS Rajshaji Kings.
I can do it using some custom looping, But I need some smart coding here and looks your attention. I think there are some ways to make it with array functions that I don't know.
You could do something like:
echo implode(' VS ', array_map(function($v) use ($arr) { return $arr[$v]; }, explode('-', $str)));
So explode the string, map the resulting array, returning the value of the matching key in $arr, then just implode it.
You could try this:-
<?php
$arr = array(
"COV" => "Comilla Victorians",
"RK" => "Rajshaji Kings"
);
$str = "COV-RK";
$values = explode("-", $str); // explode string to get keys actually
echo $arr[$values[0]] . " VS " . $arr[$values[1]]; // print desired output
Suppose I've got the following string:
) [6] => Array ( [2014-05-05 00:0] => My actual content
If I want to only be left with My actual content at the end, what is the best way to split the entire string?
Note: the words My actual content are and can change. I'm hoping to cut the string based on the second => string as this will be present at all times.
It seems you're just looking to find the first value of an array with keys you do not know. This is super simple:
Consider the following array:
$array = array(
'2014-05-22 13:36:00' => 'foo',
'raboof' => 'eh',
'qwerty' => 'value',
'8838277277272' => 'test'
);
Method #1:
Will reset the array pointer to the first element and return it.
Using reset:
var_dump( reset($array) ); //string(3) "foo"
DEMO
Method #2:
Will reset the entire array to use keys of 0, 1, 2, 3...etc. Useful if you need to get more than one value.
Using array_values:
$array = array_values($array);
var_dump( $array[0] ); //string(3) "foo"
DEMO
Method #2.5:
Will reset the entire array to use keys of 0, 1, 2, 3...etc and select the first one into the $content variable. Useful if you need to get more than one value into variables straight away.
Using list and array_values:
list( $content ) = array_values($array);
var_dump( $content ); //string(3) "foo"
DEMO
Method #3:
Arrays are iteratable, so you could iterate through it but break out immediately after the first value.
Using a foreach loop but break immediatly:
foreach ($array as $value) {
$content = $value;
break;
}
var_dump($content); //string(3) "foo"
DEMO
To Answer your question, on extracting from a string based on last 'needle'...
Okay, this is quite an arbitrary question, since it seems like you're showing us the results from a print_r(), and you could reference the array key to get the result.
However, you mentioned "... at the end", so I'm assuming My actual content is actually right at the end of your "String".
In which case there's a very simple solution. You could use: strrchr from the PHP manual - http://www.php.net/manual/en/function.strrchr.php.
So you're looking at this: strrchr($string, '=>');
Hope this answers your question. Advise otherwise if not please.
you have to use foreach loop in a foreach to get the multi dimentional array values.
foreach($value as $key){
foreach($key as $val){
echo $val;
}
}
I have two preg_match() calls and i want to merge the arrays instead of replacing the first array. my code so far:
$arr = Array();
$string1 = "Article: graphics card";
$string2 = "Price: 300 Euro";
$regex1 = "/Article[\:] (?P<article>.*)/";
$regex2 = "/Price[\:] (?P<price>[0-9]+) Euro/";
preg_match($regex1, $string1, $arr);
//output here:
$arr['article'] = "graphics card"
$arr['price'] = null
preg_match($regex2, $string2, $arr);
//output here:
$arr['article'] = null
$arr['price'] = "300"
How may I match so my output will be:
$arr['article'] = "graphics card"
$arr['price'] = "300"
?
You could use preg_replace_callback and handle the merging inside the callback function.
If it were me this is how I would do it, this would allow for easier extension at a later date, and would avoid using a callback function. It could also support searching one string easily by replacing $strs[$key] and the $strs array with a singular string var. It doesn't remove the numerical keys, but if you are only ever to go on accessing the associative keys from the array this will never cause a problem.
$strs = array();
$strs[] = "Article: graphics card";
$strs[] = "Price: 300 Euro";
$regs = array();
$regs[] = "/Article[\:] (?P<article>.*)/";
$regs[] = "/Price[\:] (?P<price>[0-9]+) Euro/";
$a = array();
foreach( $regs as $key => $reg ){
if ( preg_match($reg, $strs[$key], $b) ) {
$a += $b;
}
}
print_r($a);
/*
Array
(
[0] => Article: graphics card
[article] => graphics card
[1] => graphics card
[price] => 300
)
*/
You can use array_merge for this if you store your results in two different arrays.
But your output depicted above is not correct. You do not have $arr['price'] if you search with regex1 in your string but only $arr['article']. Same applies for the second preg_match.
That means if you store one result in $arr and one in $arr2 you can merge them into one array.
preg_match does not offer the functionality itself.
Use different array for second preg_match ,say $arr2
Traverse $arr2 as $key => $value .
Choose non null value out of $arr[$key] and $arr2[$key], and write that value to $arr[$key].
$arr will have required merged array.
This should work for your example:
array_merge( // selfexplanatory
array_filter( preg_match($regex1, $string1, $arr)?$arr:array() ), //removes null values
array_filter( preg_match($regex2, $string2, $arr)?$arr:array() )
);
Each item in my array is an array of about 5 values.. Some of them are numerical ending in "GB".. I need the same array but with "GB" stripped out so that just the number remains.
So I need to iterate through my whole array, on each subarray take each value and strip the string "GB" from it and create a new array from the output.
Can anyone recommend and efficient method of doing this?
You can use array_walk_recursive() for this:
array_walk_recursive($arr, 'strip_text', 'GB');
function strip_text(&$value, $key, $string) {
$value = str_replace($string, '', $value);
}
It's a lot less awkward than traversing an array with its values by reference (correctly).
You can create your own custom function to iterate through an array's value's, check if the substring GB exists, and if so, remove it. With that function you can pass the original array and the function into array_map
// i only did the subarray part
$diskSizes = array("500", "300 GB", "200", "120 GB", "130GB");
$newArray = array();
foreach ($diskSizes as $diskSize) {
$newArray[] = str_replace('GB', '', $diskSize);
}
// look at the new array
print_r($newArray);
$arr = ...
foreach( $arr as $k => $inner ) {
foreach( $inner as $kk => &$vv ) {
$vv = str_replace( 'GB', '', $vv );
}
}
This actually keeps the original arrays intact with the new strings. (notice &$vv, which means that i'm getting the variable by reference, which means that any changes to $vv within the loop will affect the actual string, not by copying)