Key Value Array From String - php

I have a key value pair string that I would like to convert to a functional array. So that I can reference the values using their key. Right now I have this:
$Array = "'Type'=>'Honda', 'Color'=>'Red'";
$MyArray = array($Array);
This is not bringing back a functional key/value array. My key value pairs are in a variable string which means the => is part of the string and i think this is where my problem is. Any help would be appreciated. All i am trying to do is convert the string to a functional key/value pair where I can grab the values using the key. My data is in a string so please don't reply with the answer "take them out of the string." I am aware that this will work:
$MyArray = array('Type'=>'Honda', 'Color'=>'Red');
But my probem is that the the data is already in the form of a string. Thank you for any help.

There is no direct way to do this. As such, you'll need to write a custom function to build the keys and values for each element.
An example specification for the custom function:
Use explode() to split each element based on the comma.
Iterate over the result and:
explode() on =>
Remove unnecessary characters, i.e. single quotes
Store the first element as the key and the second element as the value
Return the array.
Note: if your strings contain delimiters this will be more challenging.

You do need to "take them out of the string", as you say. But you don't have to do it manually. The other answer uses explode; that's a fine method. I'll show you another - what I think is the easiest way is to use preg_match_all() (documentation), like this:
$string = "'Type'=>'Honda', 'Color'=>'Red'";
$array = array();
preg_match_all("/'(.+?)'=>'(.+?)'/", $string, $matches);
foreach ($matches[1] as $i => $key) {
$array[$key] = $matches[2][$i];
}
var_dump($array);

You need to parse the string and extract the data:
$string = "'Type'=>'Honda', 'Color'=>'Red'";
$elements = explode(",",$string);
$keyValuePairs = array();
foreach($elements as $element){
$keyValuePairs[] = explode("=>",$element);
}
var_dump($keyValuePairs);
Now you can create your on array using the $keyValuePairs array.

Here is an example of one way you can do it -
$Array = "'Type'=>'Honda', 'Color'=>'Red'";
$realArray = explode(',',$Array); // get the items that will be in the new array
$newArray = array();
foreach($realArray as $value) {
$arrayBit = explode('=>', $value); // split each item
$key = str_replace('\'', '', $arrayBit[0]); // clean up
$newValue = str_replace('\'', '', $arrayBit[1]); // clean up
$newArray[$key] = $newValue; // place the new item in the new array
}
print_r($newArray); // just to see the new array
echo $newArray['Type']; // calls out one element
This could be placed into a function that could be extended so each item gets cleaned up properly (instead of the brute force method shown here), but demonstrates the basics.

Related

PHP - How to re-order data within a multidimensional array with only one reliable preceding string?

I am being passed inconsistent data. The problem is the individual rows of $data_array are not consistently in the same sequence but each has a reliable "text:" preceding the value.
Each row contains about 120 elements of data. I only need 24 of those elements.
It's also possible one of the elements I need could be missing, such as "cost".
(I'm using php version 5.4)
-- Task:
Using $order_array, create a new $data_array_new by reordering the data in each "row" into the same sequence as $order_array.
If an elements is missing from a row insert "NA".
Once the elements are in the correct sequence the "text" is no longer required.
$order_array = array("price", "cost", "vol", "eps")
$data_array = Array (
$one = Array ("cost":43.40, "vol":44000, "eps":1.27, "price":65.00),
$two = Array ("eps":5.14, "price":33.14, "vol":657000),
$thr = Array ("vol":650000, "cost":66.67, "eps":1.33, "price":44.31),
);
The resulting ouput should appear with the data in this order: ("price", "cost", "vol", "eps")
$data_array_new = Array (
$one = Array (65.00,43.40,44000,1.27),
$two = Array (33.14,"NA",657000,5.14),
$thr = Array (44.31,66.67,650000,1.33),
);
$data_array_new = [];
foreach ($data_array as $index => $data) {
$data_array_new[$index] = [];
foreach ($order_array as $key) {
if (isset($data[$key])) {
$data_array_new[$index][] = $data[$key];
} else {
$data_array_new[$index][] = 'NA';
}
}
}
You can view the original incoming data here: https://api.iextrading.com/1.0/stock/market/batch?symbols=aapl,tsla,ge&types=quote,earnings,stats
Here is the answer from : Andreas
Use json_decode on the string with the second parameter true and you get a associative array as output.
$url = "https://api.iextrading.com/1.0/stock/market/batch?
symbols=aapl,tsla,ge&types=quote,earnings,stats";
$arr = json_decode(file_get_contents($url), true);
Var_dump($arr);
See here;
I copied the string from the page and posted it as $str.
https://3v4l.org/duWrI
Two steps is all that is needed.

How to use string values from one array as indexes for another array in PHP

I've splitted a string into array, giving a delimitator. So, this new array created, will contain values that I would want to use as indexes for another given array.
Having a situation like this:
// my given array
$array['key1']['key2']['a_given_key']['some_other_given_key'] = 'blablabl';
// the value of my given array
$value = $array['key1']['key2']['a_given_key']['some_other_given_key'];
$string = "key1;key2";
$keys = explode(";", $string);
I want to call dinamically (during the execution of my PHP script) the value of the given array, but, using as indexes all the values of the array $keys, and in addition appending the indexes ['a_given_key']['some_other_given_key'] of my given array.
I hope I have been clear.
Many thanks.
To make it work you have to use references. Below code should work as you expect:
<?php
$string = "key1;key2;key3;key4";
$keys = explode(";", $string);
$array['key1']['key2']['key3']['key4']['a_given_key']['some_other_given_key'] = 'blablabl';
$ref = & $array;
for ($i=0, $c = count($keys); $i<$c ; ++$i) {
$ref = &$ref[$keys[$i]];
}
echo $ref['a_given_key']['some_other_given_key'];
$value = $ref['a_given_key']['some_other_given_key'];
echo $value;
?>
I would like to add that just after using reference you should unset it using:
unset($ref);
If you don't do this and many lines later you run for example $ref = 2; it will modify your source array so you have to remember about unsetting references just after it's no longer in use.

Using a delimited string, how do I get an array item?

Here's an array:
array('csv'=>
array('path'=>'/file.csv',
'lines'=>array('line1',
'line2',
'line3'
)
)
)
As you can see, the array goes three levels deep.
Here are two strings:
1. 'csv/path'
2. 'csv/lines/0
Using / as the delimiter, string 1 will get '/file.csv' and string 2 will get 'line1'. I've been thinking about using a recursive function, but I just don't know yet how to go about it.
The idea is I won't know which array key I'm accessing. I'm working on creating a generic function that will take a string as input and return the respective value in the array.
Demo
Just iterate through each key from the string given, setting the new array to pull from as the found element in the given array. You should add error handling.
<?php
$array = array('csv'=>
array('path'=>'/file.csv',
'lines'=>array('line1',
'line2',
'line3'
)
)
);
echo extractData($array, 'csv/path'); // echoes /file.csv
echo extractData($array, 'csv/lines/0'); // echoes line1
function extractData($array, $string){
$keys = explode('/', $string);
$data = $array;
foreach ($keys as $key){
$data = $data[$key];
}
return $data;
}

Can I generate an array based on url path?

I have a path like:
/blog/2/post/45/comment/24
Can I have an array depends on what I have on url, like :
$arr = array('blog'=>'2','post'=>'45','comment'=>'24');
But it should depend on variable passed:
/blog/2 should produce $arr = array('blog'=>'2');
Is this possible to create dynamic array?
You could try something like this:
function path2hash($path) {
// $path contains whatever you want to split
$chunks = explode('/', $path);
$result = array();
for ($i = 0; $i < sizeof($chunks) - 1; $i+=2)
$result[$chunks[$i]] = $chunks[$i+1];
return $result;
}
You could then use parse_url to extract the path, and this function to turn it into the desired hash.
First use $_SERVER['REQUEST_URI'] to find the current path.
now, you can use explode and other string functions to produce the array...
If you need a working example, Ill try and post one.
EDIT:
$path=explode('/',$path);
$arr=array(
$path[0]=>$path[1],
$path[1]=>$path[2]);
or don't know how long it is...
$arr=array();
for ($i=0; $i+1<count($path);i+=2)
$arr[$path[$i]]=$path[$i+1];
Here's a simple example trying to solve the issue. This will put the arguments in the "arguments" array, and will contain each combination of key/value in the array. If there's an odd number of arguments, the last element will be ignored.
This uses array_shift() to remove the first element from the array, which then is used as a key in the arguments array. We then remove the next element from the array, yet again using array_shift(). If we find an actual value here (array_shift returns NULL when the array is empty), we create a entry in the arguments array.
$path = '/blog/2/post/45/comment/24';
$elements = explode('/', $path);
// remove first, empty element
array_shift($elements);
$arguments = array();
while($key = array_shift($elements))
{
$value = array_shift($elements);
if ($value !== NULL)
{
$arguments[$key] = $value;
}
}
Not really an answer per se but you may find http://www.php.net/manual/en/function.parse-url.php useful.

How to find string elements in another string and remove them in PHP

By example:
FirstString='apple,gold,nature,grass,class'
SecondString='gold,class'
the Result must be :
ResultString='apple,nature,grass'
$first = explode(',',$firstString);
$second = explode(',',$secondString);
Now you have arrays and you can do whatever you want with them.
$result = array_diff($first, $second);
this is the easy way (for sure there must be more efficient ones):
First of all, you may want to separate those coma-separated strings and put them into an array (using the explode function):
$array1 = explode(',' $firstString);
$array2 = explode(',' $secondString);
Then, you can loop the first array and check whether it contents words of the second one using the in_array function (if so, delete it using the unset function):
// loop
foreach( $arra1 as $index => $value){
if( in_array ( $value , $array2 ) )
unset($array1[$index]); // delete that word from the array
}
Finally, you can create a new string with the result using the implode function:
$result = implode(',' , $array1);
That's it :D
I'm sure there is a function that can do it but you could always break up the strings and do a foreach on each one and do some string compares and build a new string. You could also break apart the second string and create a regular expression and do a preg_replace to replace the values in the string.

Categories