I try to convert a string containing shedule to an array
For exemple
convert("{{09:00,10:00},{18:00,19:00}}") // returns [['09:00','10:00'],['18:00','19:00']]
Is there a way more elegant than this one :
function convert($shedules) {
$shedules = explode('},{', $horaires);
$shedules = array_map(function ($shedule) {
return explode(',', str_replace(['{', '}'], '', $shedule));
}, $shedules);
return $shedules
}
Related
Given a string that contains values separated by dots:
property.entry.item
What is the best way to convert that to a key for an associative array?
$result['imported_data']['property']['entry']['item']
The string may be of any length, with any number of dots and contain an value:
people.arizona.phoenix.smith
I've tried the following without success:
//found a dot, means we are expecting output from a previous function
if( preg_match('[.]',$value)) {
//check for previous function output
if(!is_null($result['import'])) {
$chained_result_array = explode('.',$value);
//make sure we have an array to work with
if(is_array($chained_result_array)) {
$array_key = '';
foreach($chained_result_array as $key) {
$array_key .= '[\''.$key.'\']';
}
}
die(print_r(${result.'[\'import\']'.$array_key}));
}
}
I was thinking I could convert the string to a variable variable, but I get an array to string conversion error.
You can explode the string into an array and loop through the array. (DEMO)
/**
* This is a test array
*/
$testArray['property']['entry']['item'] = 'Hello World';
/**
* This is the path
*/
$string = 'property.entry.item';
/**
* This is the function
*/
$array = explode('.', $string);
foreach($array as $i){
if(!isset($tmp)){
$tmp = &$testArray[$i];
} else {
$tmp = $tmp[$i];
}
}
var_dump( $tmp ); // output = Hello World
Split the string into parts, and itterate the array, accessing each element in turn:
function arrayDotNotation($array, $dotString){
foreach(explode('.', $dotString) as $section){
$array = $array[$section];
}
return $array;
}
$array = ['one'=>['two'=>['three'=>'hello']]];
$string = 'one.two.three';
echo arrayDotNotation($array, $string); //outputs hello
Live example: http://codepad.viper-7.com/Vu8Hhy
You should really check to see if keys exist before you reference them. Otherwise, you're going to spew a lot of warnings.
function getProp($array, $propname) {
foreach(explode('.', $propname) as $node) {
if(isset($array[$node]))
$array = &$array[$node];
else
return null;
}
return $array;
}
Now you can do things like:
$x = array(
'name' => array(
'first' => 'Joe',
'last' => 'Bloe',
),
'age' => 27,
'employer' => array(
'current' => array(
'name' => 'Some Company',
)
)
);
assert(getProp($x, 'age') == 27);
assert(getProp($x, 'name.first') == 'Joe');
assert(getProp($x, 'employer.current.name') == 'Some Company');
assert(getProp($x, 'badthing') === NULL);
assert(getProp($x, 'address.zip') === NULL);
Or, if you are only interested in the import section of the tree:
getProp($x['import'], 'some.path');
I have this string:
"[\"form\",\"form-elements\"], [\"company\",\"asdasd\"], [\"cod_postal\",\"051768\"], [\"recaptcha_challenge_field\",\"03AHJ_VuvJZjfMzRQolI_QhGijJqAEcRPswuz9l68I6VStJzTbuK4ilos06TIQKVsIy2vpe1PEq-Q5KBVlZ5xt4HM5VoJSWUgFTGVbtbmARtKiMvO4WZh57X0-QVDyQ5Lq-ZM8rMqB5O2-rCbnyw_UAGbbV1ZElsI4kuLk4ei6mzLtqgcU2VAR64tySiKPARDtahiTBKWePH2rjKO6KUBQTRE49TMjIGb5hg8sbYguKBSUrRF6G86b89M\"], [\"recaptcha_response_field\",\"168\"]"
This string was formated form an array using this code:
function arrayDisplay($input)
{
return implode(
', ',
array_map(
function ($v, $k) {
return sprintf('["%s","%s"]', $k, $v);
},
$input,
array_keys($input)
)
);
}
And encoded using :
$xml_array = arrayDisplay($_POST);
$xml_encode = json_encode($xml_array);
And this is the array in $_POST variable:
array (size=5)
'form' => string 'form-elements' (length=13)
'company' => string 'asdasd' (length=6)
'cod_postal' => string '051768' (length=6)
'recaptcha_challenge_field' => string '03AHJ_VuvJZjfMzRQolI_QhGijJqAEcRPswuz9l68I6VStJzTbuK4ilos06TIQKVsIy2vpe1PEq-Q5KBVlZ5xt4HM5VoJSWUgFTGVbtbmARtKiMvO4WZh57X0-QVDyQ5Lq-ZM8rMqB5O2-rCbnyw_UAGbbV1ZElsI4kuLk4ei6mzLtqgcU2VAR64tySiKPARDtahiTBKWePH2rjKO6KUBQTRE49TMjIGb5hg8sbYguKBSUrRF6G86b89M' (length=249)
'recaptcha_response_field' => string '168' (length=3)
First I want to wrap the entire string replacing "" with [] :
[[\"form\",\"form-elements\"], [\"company\",\"asdasd\"], [\"cod_postal\",\"051768\"], [\"recaptcha_challenge_field\",\"03AHJ_VuvJZjfMzRQolI_QhGijJqAEcRPswuz9l68I6VStJzTbuK4ilos06TIQKVsIy2vpe1PEq-Q5KBVlZ5xt4HM5VoJSWUgFTGVbtbmARtKiMvO4WZh57X0-QVDyQ5Lq-ZM8rMqB5O2-rCbnyw_UAGbbV1ZElsI4kuLk4ei6mzLtqgcU2VAR64tySiKPARDtahiTBKWePH2rjKO6KUBQTRE49TMjIGb5hg8sbYguKBSUrRF6G86b89M\"], [\"recaptcha_response_field\",\"168\"]]
And exclude [\"form\",\"form-elements\"] , [\"recaptcha_challenge_field\",\"03AHJ_VuvJZjfMzRQolI_QhGijJqAEcRPswuz9l68I6VStJzTbuK4ilos06TIQKVsIy2vpe1PEq-Q5KBVlZ5xt4HM5VoJSWUgFTGVbtbmARtKiMvO4WZh57X0-QVDyQ5Lq-ZM8rMqB5O2-rCbnyw_UAGbbV1ZElsI4kuLk4ei6mzLtqgcU2VAR64tySiKPARDtahiTBKWePH2rjKO6KUBQTRE49TMjIGb5hg8sbYguKBSUrRF6G86b89M\"] and [\"recaptcha_response_field\",\"168\"]
What I can use to do that and how ?
You must filter the input. After filtering it you just return the json encoded string:
function arrayDisplay($input)
{
$input = array_filter($input, function ($key) {
return !in_array($key, array('form', 'recaptcha_challenge_field', 'recaptcha_response_field'));
}, ARRAY_FILTER_USE_KEY);
return json_encode(array($input));
}
If you still want to return the key-value pairs separated by comma then keep the original implode function and concatenate the result with the squared brackets:
function arrayDisplay($input)
{
$input = array_filter($input, function ($key) {
return !in_array($key, array('form', 'recaptcha_challenge_field', 'recaptcha_response_field'));
}, ARRAY_FILTER_USE_KEY);
return '[' . implode(
', ',
array_map(
function ($v, $k) {
return sprintf('["%s","%s"]', $k, $v);
},
$input,
array_keys($input)
)
) . ']';
}
Please note that $xml_encode = json_encode($xml_array); makes no sense as the returned string is "almost" a valid json encoded string (in the original function). If this is your intention then you must use the first function I wrote and remove that line of code that is encoding again the returned value.
You should start from your $_POST array, and take the keys from it you really need:
$input = $_POST;
unset($input["form"]);
unset($input["recaptcha_challenge_field"]);
unset($input["recaptcha_response_field"]);
Now that $input array looks like this:
array(
"company" => "asdasd",
"cod_postal" => "051768"
);
Then, I would change the definition of your arrayDisplay function without altering its functionality, by splitting it into 2:
function arrayPairs($input) {
return array_map(
function ($v, $k) {
return [$k,$v];
},
$input,
array_keys($input)
);
}
function arrayDisplay($input) {
return implode (", ", array_map('json_encode', arrayPairs($input)));
}
This arrayDisplay function still returns the same values as before, but you can now also call arrayPairs without conversion to string. Instead you would do that conversion with json_encode which gives exactly the output you want:
echo json_encode(arrayPairs($input));
This outputs:
[["company","asdasd"],["cod_postal","051768"]]
NB: If you don't use the arrayDisplay function for any other purpose, then you can do away with it. This solution only uses the function arrayPairs.
I made some changes and ended up with this:
function arrayDisplay($input)
{
$goodKeys = array_diff(array_keys($input), array('form', 'recaptcha_challenge_field', 'recaptcha_response_field'));
var_dump($goodKeys);
$data = [];
foreach ($goodKeys as $goodKey) {
$data[$goodKey] = $input[$goodKey];
}
return '[' . implode(
', ',
array_map(
function ($v, $k) {
return sprintf('["%s","%s"]', $k, $v);
},
$data,
array_keys($data)
)
) . ']';
}
but now there is one more problem, I need to get rid of "" this 2 from the start/end of the string:
from this:
"[[\"company\",\"123\"], [\"cod_postal\",\"051768\"]]"
to this:
[[\"company\",\"123\"], [\"cod_postal\",\"051768\"]]
Given a string that contains values separated by dots:
property.entry.item
What is the best way to convert that to a key for an associative array?
$result['imported_data']['property']['entry']['item']
The string may be of any length, with any number of dots and contain an value:
people.arizona.phoenix.smith
I've tried the following without success:
//found a dot, means we are expecting output from a previous function
if( preg_match('[.]',$value)) {
//check for previous function output
if(!is_null($result['import'])) {
$chained_result_array = explode('.',$value);
//make sure we have an array to work with
if(is_array($chained_result_array)) {
$array_key = '';
foreach($chained_result_array as $key) {
$array_key .= '[\''.$key.'\']';
}
}
die(print_r(${result.'[\'import\']'.$array_key}));
}
}
I was thinking I could convert the string to a variable variable, but I get an array to string conversion error.
You can explode the string into an array and loop through the array. (DEMO)
/**
* This is a test array
*/
$testArray['property']['entry']['item'] = 'Hello World';
/**
* This is the path
*/
$string = 'property.entry.item';
/**
* This is the function
*/
$array = explode('.', $string);
foreach($array as $i){
if(!isset($tmp)){
$tmp = &$testArray[$i];
} else {
$tmp = $tmp[$i];
}
}
var_dump( $tmp ); // output = Hello World
Split the string into parts, and itterate the array, accessing each element in turn:
function arrayDotNotation($array, $dotString){
foreach(explode('.', $dotString) as $section){
$array = $array[$section];
}
return $array;
}
$array = ['one'=>['two'=>['three'=>'hello']]];
$string = 'one.two.three';
echo arrayDotNotation($array, $string); //outputs hello
Live example: http://codepad.viper-7.com/Vu8Hhy
You should really check to see if keys exist before you reference them. Otherwise, you're going to spew a lot of warnings.
function getProp($array, $propname) {
foreach(explode('.', $propname) as $node) {
if(isset($array[$node]))
$array = &$array[$node];
else
return null;
}
return $array;
}
Now you can do things like:
$x = array(
'name' => array(
'first' => 'Joe',
'last' => 'Bloe',
),
'age' => 27,
'employer' => array(
'current' => array(
'name' => 'Some Company',
)
)
);
assert(getProp($x, 'age') == 27);
assert(getProp($x, 'name.first') == 'Joe');
assert(getProp($x, 'employer.current.name') == 'Some Company');
assert(getProp($x, 'badthing') === NULL);
assert(getProp($x, 'address.zip') === NULL);
Or, if you are only interested in the import section of the tree:
getProp($x['import'], 'some.path');
Lets say I have an array like this, it could be multi-dimensional so I do need to make this loop recursive.
I think I'm close but can't quite see where I'm wrong.
[
{ "value": "rigging" },
{ "value": "animation" },
{ "value": "modeling" }
]
function _replace_amp($post = array()) {
foreach($post as $key => $value)
{
if (is_array($value)) {
$b = $this->_replace_amp($value);
} else {
$b .= $value . ', ';
}
}
return $b;
}
The intended result should be:
"rigging, animation, modeling"
I'm getting just "modeling,"
In your code, you need to write
$b .= $this->_replace_amp($value); // note the period
Without the period, you are initiating $b every time your script finds a new array, but you want to append the results to $b.
Other than that, there is a nice implode function for multidimensional arrays available:
/**
* Recursively implodes an array with optional key inclusion
*
* Example of $include_keys output: key, value, key, value, key, value
*
* #access public
* #param array $array multi-dimensional array to recursively implode
* #param string $glue value that glues elements together
* #param bool $include_keys include keys before their values
* #param bool $trim_all trim ALL whitespace from string
* #return string imploded array
*/
function recursive_implode(array $array, $glue = ',', $include_keys = false, $trim_all = true)
{
$glued_string = '';
// Recursively iterates array and adds key/value to glued string
array_walk_recursive($array, function($value, $key) use ($glue, $include_keys, &$glued_string)
{
$include_keys and $glued_string .= $key.$glue;
$glued_string .= $value.$glue;
});
// Removes last $glue from string
strlen($glue) > 0 and $glued_string = substr($glued_string, 0, -strlen($glue));
// Trim ALL whitespace
$trim_all and $glued_string = preg_replace("/(\s)/ixsm", '', $glued_string);
return (string) $glued_string;
}
Source: https://gist.github.com/jimmygle/2564610
I think either json_encode( your_php_array ) or serialize() function is help you.
You want to use function implode(). No need to re-invent the wheel.
<?php
$arr = ['one', 'two', 'three'];
echo implode(',', $arr); // one, two, three
$b = $this->_replace_amp($value); change in this line to $b .= $this->_replace_amp($value);
this answer as per your coding
[
{ "value": "rigging" },
{ "value": "animation" },
{ "value": "modeling" }
]
function _replace_amp($post = array()) {
foreach($post as $key => $value)
{
if (is_array($value)) {
$b .= $this->_replace_amp($value);
} else {
$b .= $value . ', ';
}
}
return $b;
}
batter way to do this using used implode(',',$array);
How can I get part of the string with conditional prefix [+ and suffix +], and then return all of it in an array?
example:
$string = 'Lorem [+text+] Color Amet, [+me+] The magic who [+do+] this template';
// function to get require
function getStack ($string, $prefix='[+', $suffix='+]') {
// how to get get result like this?
$result = array('text', 'me', 'do'); // get all the string inside [+ +]
return $result;
}
many thanks...
You can use preg_match_all as:
function getStack ($string, $prefix='[+', $suffix='+]') {
$prefix = preg_quote($prefix);
$suffix = preg_quote($suffix);
if(preg_match_all("!$prefix(.*?)$suffix!",$string,$matches)) {
return $matches[1];
}
return array();
}
Code In Action
Here’s a solution with strtok:
function getStack ($string, $prefix='[+', $suffix='+]') {
$matches = array();
strtok($string, $prefix);
while (($token = strtok($suffix)) !== false) {
$matches[] = $token;
strtok($prefix);
}
return $matches;
}