How to find strings and add these string to an array - php

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

Related

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

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

Foreach through multidimensional array with dynamic/unknown dimensions

I'm trying to loop through a multidimensional array with foreach but sometimes there's 5 dimensions and sometimes there's 2, but I need to foreach every array. Here is an example:
array(16) {
["id"]=>
string(2) "1"
["name"]=>
string(1) "Bob"
["job"]=>
array(2) {
[0]=>
string(8) "software"
[1]=>
string(7) "plumber"
}
["kids"]=>
array(2) {
[1]=>
array(2) {
[0]=>
string(4) "Jane"
[1]=>
string(4) "girl"
}
[2]=>
array(2) {
[0]=>
string(3) "Sam"
[1]=>
string(4) "boy"
[2] => array(2) {
[0]=>
string(3) "123"
[1]=>
string(11) "Main Street"
}
}
}
}
you get the point.... but imagine if I had a dimension of 10 in the array. How can I dynamically loop through them and do trim() to each value in the whole array?
Here is what I have so far:
foreach ($array as $key => $value) {
$array[$key] = trim($value);
}
but I need it to go deeper into an array if there is an array and perform trim to all values in my $array.

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

How to add key name in nested arrays?

I have the following array:
array(5) {
[0]=> array(3) {
[0]=> string(10) "2013-09-18"
[1]=> string(75) "Ready For Retina HD: Create Pixel-Perfect Assets For Multiple Scale Factors"
[2]=> string(74) "ready-for-retina-hd-create-pixel-perfect-assets-for-multiple-scale-factors"
}
[1]=> array(3) {
[0]=> string(10) "2010-10-20"
[1]=> string(40) "Taking A Closer Look At Tech Conferences"
[2]=> string(40) "taking-a-closer-look-at-tech-conferences"
}
[2]=> array(3) {
[0]=> string(10) "2014-10-19"
[1]=> string(29) "Wayfinding For The Mobile Web"
[2]=> string(29) "wayfinding-for-the-mobile-web"
}
[3]=> array(3) {
[0]=> string(10) "2014-05-15"
[1]=> string(24) "Freebie: Icons Of Autumn"
[2]=> string(23) "freebie-icons-of-autumn"
}
[4]=> &array(1){
[0]=> string(0) ""
}
}
How would I go about assigning key names to each part of the inner array? E,g date, title, pathname.
I understand you can do something like this to create an array with certain keys, but how does this work with multiple nested arrays? And how can it be assigned after array creation?
$keys = array('Date', 'Title', 'Filepath');
Assuming $array1 is your main array (with 5 values).
foreach($array1 as $a)
{
if (len($a) == 3)
$array2[] = array("Date" => $a[0], "Title" => $a[1], "Filepath" => $a[2]);
}
$array1 = $array2;
Use a foreach.
$new = [];
foreach ($origArray as $inner) {
$new[] = [
"date" => $inner[0],
"title" => $inner[1],
"filepath" => $inner[2]
];
}
$origArray = $new;
This doesn't handle cases where the item does not conform to the "standard" (e.g item 4) but this should get you started.

How to add key to an existing array (PHP)

I have an existing array (as seen below)...
array(15) {
[0]=>
string(17) "orderid:100000154"
[1]=>
string(61) "shipping_method:channelunitycustomrate_channelunitycustomrate"
[2]=>
string(18) "qty_ordered:1.0000"
[3]=>
string(26) "shipping_firstname:John"
[4]=>
string(24) "shipping_lastname:Doe"
[5]=>
string(17) "shipping_company:"
[6]=>
string(36) "shipping_street1:123 Fake Street"
[7]=>
string(17) "shipping_street2:"
[8]=>
string(20) "shipping_city:LAUREL"
[9]=>
string(28) "shipping_postcode:20723-1042"
[10]=>
string(24) "shipping_region:Maryland"
[11]=>
string(19) "shipping_country:US"
[12]=>
string(21) "vendor_sku:3397001814"
[13]=>
string(16) "vendor_linecode:"
[14]=>
string(1) "
"
}
I have a desired key setup in this array -- the key for the first value would be orderid, so I'd like orderid => 1000000154
How would I go about this? I believe I have to explode the array again, but I'm not sure about the way to write it and none of my attempts have gotten me any closer.
Thanks!
Just loop through and set the keys and values using explode(). Use the first item in the exploded array as the key and the second as the value, then unset the existing item (the numeric-indexed array element) to clean up.
$input = array(
"orderid:100000154",
"shipping_method:channelunitycustomrate_channelunitycustomrate",
"qty_ordered:1.0000",
"shipping_firstname:John",
"shipping_lastname:Doe",
"shipping_company:",
"shipping_street1:123 Fake Street",
"shipping_street2:",
"shipping_city:LAUREL",
"shipping_postcode:20723-1042",
"shipping_region:Maryland",
"shipping_country:US",
"vendor_sku:3397001814",
"vendor_linecode:",
"
"
);
foreach($input as $key => $val) {
if(strstr($val, ":")) {
$exploded = explode(":", $val);
$input[$exploded[0]] = $exploded[1];
}
unset($input[$key]);
}
echo "<pre>";
var_dump($input);
echo "</pre>";
Outputs:
array(14) {
["orderid"]=>
string(9) "100000154"
["shipping_method"]=>
string(45) "channelunitycustomrate_channelunitycustomrate"
["qty_ordered"]=>
string(6) "1.0000"
["shipping_firstname"]=>
string(4) "John"
["shipping_lastname"]=>
string(3) "Doe"
["shipping_company"]=>
string(0) ""
["shipping_street1"]=>
string(15) "123 Fake Street"
["shipping_street2"]=>
string(0) ""
["shipping_city"]=>
string(6) "LAUREL"
["shipping_postcode"]=>
string(10) "20723-1042"
["shipping_region"]=>
string(8) "Maryland"
["shipping_country"]=>
string(2) "US"
["vendor_sku"]=>
string(10) "3397001814"
["vendor_linecode"]=>
string(0) ""
}
$result = array();
foreach($yourArray as $row) {
list($key, $value) = explode(":", $row);
$result[$key] = $value;
}

Categories