How can I turn this string into a key value array? - php

I have a string like the one below, including the parenthesis:
("string" "value" "string" "value" "string" "value" ...)
The number of quoted parts are unknown with a minimum of one pair, I would like to turn this into an associative array, my desired result is:
array('string'=>$value,'string'=>$value, 'string'=>$value)
How could I do this? Preferably, I would like to use a built-in function or a one liner or create a custom function, any help would be appreciated.

How to use build-in functions :)
$str = '("string" "value" "string1" "value1" "string2" "value2")';
$str = preg_replace('~^\("|"\)$~', '', $str);
$ar = explode('" "', $str);
$ar = array_chunk($ar,2);
$ar = array_column($ar, 1, 0);
print_r($ar);
demo

<?php
$str='("foo" "bar" "ying" "yang" "apple" "orange")';
$cols = str_getcsv(trim($str, '()'), ' ');
$chunked = array_chunk($cols, 2);
$result = array_column($chunked, 1, 0);
var_dump($cols, $chunked, $result);
Output:
array(6) {
[0]=>
string(3) "foo"
[1]=>
string(3) "bar"
[2]=>
string(4) "ying"
[3]=>
string(4) "yang"
[4]=>
string(5) "apple"
[5]=>
string(6) "orange"
}
array(3) {
[0]=>
array(2) {
[0]=>
string(3) "foo"
[1]=>
string(3) "bar"
}
[1]=>
array(2) {
[0]=>
string(4) "ying"
[1]=>
string(4) "yang"
}
[2]=>
array(2) {
[0]=>
string(5) "apple"
[1]=>
string(6) "orange"
}
}
array(3) {
["foo"]=>
string(3) "bar"
["ying"]=>
string(4) "yang"
["apple"]=>
string(6) "orange"
}

One way is to match the pattern of a pair of quoted strings, then fill the result array in a callback function using the two strings from the match.
preg_replace_callback('/"([^"]+)" "([^"]+)"/', function($match) use (&$result) {
$result[$match[1]] = $match[2];
}, $str);

Related

PHP : How to include another array's elements in another array's index?

I have two arrays:
array(3)
{
[0]=>
string(1) "1"
[1]=>
string(1) "1"
[2]=>
string(1) "2"
}
array(3)
{
[0]=>
string(1) "abc"
[1]=>
string(1) "def"
[2]=>
string(1) "ghi"
}
Is there any way I could put the first array's elements into the second array's index producing the following result :
array(3)
{
[1]=>
string(1) "abc"
[1]=>
string(1) "def"
[2]=>
string(1) "ghi"
}
How can I do this in PHP? Thanks in advance.
Since the expected output is impossible the next best thing it to make a multidimensional array where the question id is a subarray for answers.
$arr1 = [1,1,2];
$arr2 = ["abc","def","ghi"];
Foreach($arr1 as $key => $id){
$threads[$id][] = $arr2[$key];
}
Var_dump($threads)
Outputs:
array(2) {
[1]=>
array(2) {
[0]=> "abc"
[1]=> "def"
}
[2]=>
array(1) {
[0]=> "ghi"
}
}
https://3v4l.org/qpJDA
You can use "array_combine" method for this purpose.
http://php.net/array-combine
However, you cannot have same multiple indexes in an array
array(3)
{
[1]=> "abc"
[1]=> "def"
[2]=> "ghi"
}
You have index "1" twice in array. So "def" will replace "abc" in your array

How can I detect the differences between two arrays?

I have two arrays, I would like to compare.
array1:
array(4) {
["123"]=>
array(5) {
["animal"]=>
string(2) "cat"
["name"]=>
string(4) "fred"
}
["345"]=>
array(5) {
["animal"]=>
string(3) "dog"
["name"]=>
string(4) "alan"
}
["order"]=>
string(2) "12"
}
array2:
array(4) {
["123"]=>
array(5) {
["animal"]=>
string(2) "cat"
["name"]=>
string(4) "fred"
}
["345"]=>
array(5) {
["animal"]=>
string(3) "fox"
["name"]=>
string(4) "tom"
}
["order"]=>
string(2) "12"
}
I compare them with array_diff:
$result = array_diff($array1, $array2);
But if I var_dump $result, I get the following output:
array(0) {
}
Does anyone have an idea why?
For associative arrays you should use array_diff_assoc. Also see the user contributed notes for how to do this recursively, if you need to.
With the help of sinaza I found out that no difference was displayed, because array_diff works different with multidimensional arrays.
Here is the code, that worked for me:
foreach ($array1 as $k1 => $v1) {
if (array_diff($array2[$k1], $array1[$k1])){
$result[$k1] = array_diff($array2[$k1], $array1[$k1]);
}
}

Split Values in Array Using Explode to form Multidimensional Array

I am new to PHP so be kind. :)
I have a 3 deep array. Something like this:
Array(5) {
[0]=> array(5) {
[0]=> string(0) ""
[1]=> string(21) "0,245.19000000,864432"
[2]=> string(21) "1,245.26000000,864432"
[3]=> string(21) "2,245.49000000,864432"
[4]=> string(21) "4,245.33000000,864432"
}
[1]=> array(5) {
[0]=> string(0) ""
[1]=> string(21) "0,245.19000000,864453"
[2]=> string(21) "1,245.26000000,864453"
[3]=> string(21) "2,245.49000000,864453"
[4]=> string(21) "4,245.33000000,864453"
}
}...
I want to explode the inner string by commas ("2,245.49000000,864453") so the arrays becomes 4 deep like so:
Array(5) {
[0]=> array(5) {
[0]=> string(0) ""
[1]=> array (3)
[0]=> "0"
[1]=> "245.19000000"
[2]=> "864432"
[2]=> array (3)
[0]=> "1"
[1]=> "245.26000000"
[2]=> "864432"
[3]=> array (3)
[0]=> "3"
[1]=> "245.49000000"
[2]=> "864432"
[4]=> array (3)
[0]=> "4"
[1]=> "245.3000000"
[2]=> "864432"
[4]=> array (3)
[0]=> "5"
[1]=> "245.3300000"
[2]=> "864432"
}
}
...
So far I have:
$done = array();
for ($i = 0; $i<=count($chunks); $i++) { //loops to get size of each 2d array
$r = count($chunks[$i]);
for ($c = 0; $c<=count($chunks[$r]); $c++) { //loops through 3d array
$arrayparts = $chunks[$i][$c];
$done[] = explode(",", $arrayparts); //$arrayparts is 3d array string that is exploded each time through loop
}
}
I think this code should work but when I var_dump nothing prints?
Can someone help me learn?
Thanks!
Suggested:
$chunks is 3d array
foreach($chunks as $innerArray) {
$result[] = array_map(function($v){
return explode(",", $v);
}, $innerArray);
}
Don't make it complicated, just use this:
(Here I go through each innerArray with a foreach loop and then I go through all values with array_map() and explode it and return it to the results array)
<?php
foreach($arr as $innerArray) {
$result[] = array_map(function($v){
return explode(",", $v);
}, $innerArray);
}
print_r($result);
?>
This uses array_map() two times. Maybe a better way but I'm on beer three:
$result = array_map(function($v){
return array_map(function($v){ return explode(',', $v); }, $v);
}, $array);

One element in array php , how to explode it?

I have an array of links:
('url1','url2','url3')
But sometimes it's going to be only one link e.g. ('url')
So how do i have to get the url if its only one because i'm using explode with comma?
$input = "('url1','url2','url3')";
preg_match_all("~'(.*?)'~", $input, $output);
var_dump( $output);
//array(2) { [0]=> array(3) { [0]=> string(6) "'url1'" [1]=> string(6) "'url2'" [2]=> string(6) "'url3'" } [1]=> array(3) { [0]=> string(4) "url1" [1]=> string(4) "url2" [2]=> string(4) "url3" } }
and
$input = "('url1')";
preg_match_all("~'(.*?)'~", $input, $output);
var_dump( $output);
//array(2) { [0]=> array(1) { [0]=> string(6) "'url1'" } [1]=> array(1) { [0]=> string(4) "url1" } }

How to find strings and add these string to an array

Anyone please help me..
$description = "This is product description. Quality is good. Title:title Price:1000 Size:XL, Medium, Small Color:red, green, blue. Any one can buy freely. ";
I wanna find "Title:", "Price:", "Size:" and "Color:" from that string and I want to add those values in an array.
My desired output is:
$new_desc = array(
'title'=>'title',
'price'=>1000,
'size'=>array(
[0]=>'XL',
[1]=>'Medium',
[2]=>'Small',
),
'color'=>array(
[0]=>'red',
[1]=>'green',
[2]=>'blue',
),
);
Thanks a lot!!!
Using preg_match_all, you can find you your identifiers (Price, Size ...) and their Values. You then just have to alter that to fit your array form.
Read up on preg_match_all and Regular Expressions.
<?php
$string = "This is product description. Quality is good. Title:title Price:1000 Size:XL, Medium, Small Color:red, green, blue. Any one can buy freely. ";
preg_match_all('/([^ ]{1,}):(([0-9a-z]{1,}|([0-9a-z,]{1,})( ))+)/i', $string, $matches);
var_dump($matches);
So this gives you:
array(6) {
[0]=>
array(4) {
[0]=>
string(11) "Title:title"
[1]=>
string(10) "Price:1000"
[2]=>
string(22) "Size:XL, Medium, Small"
[3]=>
string(22) "Color:red, green, blue"
}
[1]=>
array(4) {
[0]=>
string(5) "Title"
[1]=>
string(5) "Price"
[2]=>
string(4) "Size"
[3]=>
string(5) "Color"
}
[2]=>
array(4) {
[0]=>
string(5) "title"
[1]=>
string(4) "1000"
[2]=>
string(17) "XL, Medium, Small"
[3]=>
string(16) "red, green, blue"
}
[3]=>
array(4) {
[0]=>
string(5) "title"
[1]=>
string(4) "1000"
[2]=>
string(5) "Small"
[3]=>
string(4) "blue"
}
[4]=> [...]
}
if you iterate over the first set of matches from this array, you can create your desired output easily using stripos to find occurances of , and explode to generate arrays from your , seperated values.
$new_desc = array();
foreach ($matches[1] as $index => $identifier) {
$value = $matches[2][$index];
if(stripos($value, ',') !== FALSE) {
$value = explode(',',$value);
}
$new_desc[$identifier] = $value;
}
var_dump($new_desc);
The full working DEMO can be found here.
Use preg_match_all() to extract the key value pairs first:
preg_match_all('/[A-Z][a-z]+:[a-z\d, ]+/', $description, $matches);
Then loop through the $matches array and use explode() to create your result array:
foreach ($matches[0] as $value) {
list($key, $qty) = explode(':', $value);
if (strpos($qty, ',') !== FALSE) {
$result[strtolower($key)] = array_map('trim', explode(',', $qty));
} else {
$result[strtolower($key)] = trim($qty);
}
}
var_dump($result);
Output:
array(3) {
["title"]=>
string(5) "title"
["price"]=>
string(4) "1000"
["color"]=>
array(3) {
[0]=>
string(3) "red"
[1]=>
string(5) "green"
[2]=>
string(4) "blue"
}
}
Demo

Categories