How to create multidimensional PHP array from this string? - php

I have a string I would like to separate and make a multidimensional array out of. The string looks like this:
$string = "item-size:large,color:blue,material:cotton,item-size:medium,color:red,material:silk,";
Unfortunately, I have no control over how the string is put together, which is why I'm trying to make this array.
My goal is to make an array like this:
$item[1]['color'] // = blue
$item[2]['material'] // = silk
So, here's what I've done:
$item = array();
$i=0; // I know this is messy
$eachitem = explode("item-",$string);
array_shift($eachitem); // get rid of the first empty item
foreach ($eachitem as $values) {
$i++; // Again, very messy
$eachvalue = explode(",",$values);
array_pop($eachvalue); // get rid of the last comma before each new item
foreach ($eachvalue as $key => $value) {
$item[$i][$key] = $value;
}
}
I'm obviously lost with this... any suggestions?

You're mostly there. Just replace your inner foreach with
foreach ($eachvalue as $value) {
$properties = explode(':', $value);
$item[$i][$properties[0]] = $properties[1];
}

You're close, this is how I would do it:
$string = "item-size:large,color:blue,material:cotton,item-size:medium,color:red,material:silk,";
$substr = explode("item-", $string);
$items = array();
foreach ($substr as $string) {
$subitems = array();
$pairs = explode(",", $string);
foreach ($pairs as $pair) {
list($key, $value) = explode(":", $pair, 2);
$subitems[$key] = $value;
}
$items[] = $subitems;
}
var_dump($items);
Using list here is great :) Do note that you would need the extra count limiter in explode else you might lose data if there are more :.

$array = array();
$string = explode(',', $string);
foreach($string as $part):
$part = trim($part);
if(strlen($part) < 3) continue;
$part = explode(':', $part);
$array[$part[0]] = $part[1];
endforeach;

$string = "item-size:large,color:blue,material:cotton,item-size:medium,color:red,material:silk,";
$num_attr = 3;
$item = array();
$i=$x=0;
foreach(explode(',', trim($string,',')) as $attr)
{
list($key, $value) = explode(':', $attr);
$item[$x+=($i%$num_attr==0?1:0)][$key] = $value;
$i++;
}
Set the $num_attr to the number of item attributes in the string (this will allow adjustments in the future if they grow/shrink). The trim inside the foreach is removing ay "empty" data like the last comma (it will also remove a empty first comma if one ever shows up). The crazy looking $item[$x+=($i%$num_attr==0?1:0)] is taking the modulus of the counter / number of attributes which when it is 0 that means we are on a new product line so we add 1 to x which populates the item number index, if the modulus returns a number then we know we are on the same product so we add 0 which doesn't change the items index so that attribute is added on to the same item.

Related

“How can to fix the problem ‘ number_format error

I would like to shorten the result. I have used nummber_format but always an error appears.Can someone help me.
$arr = array();
foreach ($order->orderPositions as $tax) {
$arr[] = $tax->tax;
}
$unique_data = array_unique($arr);
foreach ($unique_data as $val) {
$totalTaxes[$val] = $order->orderPositions->where('tax',
$val)->sum('TotalPriceWithTax');
}
/*help is needed here*/ number_format((float)$unique_data,2);
Loop the array and save them as the new format either in a new array or the same
$unique_data = array_unique($arr);
foreach ($unique_data as &$val) { //notice the & if you want to change the data points in the unique array
$totalTaxes[$val] = $order->orderPositions->where('tax', $val)->sum('TotalPriceWithTax');
$val = number_format($val,2); // replaces the data in unique array
$new[] = number_format($val,2); // add to new array if you need unique array
}

PHP get parameters from URL and convert to array

CASE:
I'm trying to get ordered items and quantity from another page, so I'm passing it using GET (http://foo.bar/?view=process-order&itm=1&qty=1000...), then I must to take this parameters and convert to an multidimensional array following this sequence:
EXPECTED:
URL will be: http://foo.bar/?view=foo-bar&itm=1&qty=1000&itm=2&qty=3000&itm=3&qty=1850
[0]=>
[itm]=>'1',
[qty]=>'1000',
[1]=>
[itm]=>'2',
[qty]=>'3000',
[2]=>
[itm]=>'3';
[qty]=>'1850',
etc.
CODE:
$url = $_SERVER['REQUEST_URI']; //get the URL
$items = parse_url($url, PHP_URL_QUERY); //get only the query from URL
$items = explode( '&', $items );//Explode array and remove the &
unset($items[0]); //Remove view request from array
$items = implode(",", $items); //Implode to a string and separate with commas
list($key,$val) = explode(',',$items); //Explode and remove the commas
$items = array($key => $val); //Rebuild array
ACTUAL RESULT:
[itm=1] => [qty=1000]
ACTUAL BEHAVIOUR:
Result leave only the first element in the array and make it like array({[itm=1]=>[qty=1000]}) that anyway isn't what I need.
Even If I've read much pages of PHP docs can't find the solution.
Thanks to all who can help
Your statement list($key,$val) = explode(',',$items); will only fetch the first two items in an array.
Here's a rewritten version
$chunks = explode('&', $_SERVER['QUERY_STRING']);
$items = array();
$current = -1; // so that entries start at 0
foreach ($chunks as $chunk) {
$parts = explode('=', $chunk);
if ($parts[0] == 'itm') {
$current++;
$items[$current]['itm'] = urldecode($parts[1]);
}
elseif ($parts[0] == 'qty') {
$items[$current]['qty'] = urldecode($parts[1]);
}
}
print_r($items);
Here is another version. I only modified the bottom part of your code (first 4 lines are untouched).
$url = $_SERVER['REQUEST_URI']; //get the URL
$items = parse_url($url, PHP_URL_QUERY); //get only the query from URL
$items = explode('&', $items );//Explode array and remove the &
unset($items[0]); //Remove view request from array
$list = array(); // create blank array for storing data
foreach ($items as $item){
list($key, $val) = explode('=', $item);
if ($key === 'itm')
$list[] = ['itm' => $val];
else // qty
$list[count($list) - 1]['qty'] = $val;
}
Hope this helps.

PHP filter links

i have this array
$array = array(
"http://www.mywebsite.com/eternal_link_1",
"http://www.mywebsite.com/eternal_link_2/",
"http://www.mywebsite.com/eternal_link_1/#",
"http://subdomain1.mywebwite.com",
"http://subdomain2.mywebwite.com/eternal_link",
"http://www.external-link.com"
);
$eternal_links = array();
$subdomain_links = array();
$external_links = array();
how i can filter $array and add the values to the 3 arrays above?
You can use strpos to find the correct string.
foreach($array as $item){
if(strpos($item, 'external') == TRUE){
array_push($external_links, $item);
}
// and go on..
}

Explode the string value by using the index value in PHP

I have a string that has been concatenated by the rows and columns that has be separated by using the special characters. Below is my code:
$strMaterialDetails = '13-"9"Strawberry%*DEALER%*15%*25%*375%*7.500%*7.500%*28.13%*2.000%*2.000%*6.94#^$14-"9" Yellow white Acrylic Long Pile Ext Roller Set%*DISTRIBUTOR%*45%*75%*3375%*2.500%*2.500%*84.38%*5.000%*5.000%*164.53#^$';
$pairs = explode('#^$', $strMaterialDetails);
foreach ($pairs as $pair) {
list($product, $store, $qty, $unit, $total_price, $discount, $discount_percen, $discount_value, $tax, $tax_percen, $tax_val) = explode('%*', $pair);
echo $store;
}
It works fine I have to insert the values into the database if I print the $store it will print DEALERDISTRIBUTOR
I want to seperate this I don't know how to do. The string here entered is unknown.
Please give any suggestion.
Why not store it in an array?
$stores = array();
foreach ($pairs as $pair) {
list($product,$store,$qty,$unit,$total_price,$discount,$discount_percen,$discount_value,$tax,$tax_percen,$tax_val) = explode('%*', $pair);
$stores[] = $store;
}
print_r($stores); // will contain DEALER at 0th index and DISTRIBUTOR at 1st index
DEMO
Your DEALERDISTRIBUTOR is not store in $store
actualy you are printing the $store in loop without any space that why it is printing combine.
originaly in first loop $store=DEALER then you echo it. and in second loop $store=DISTRIBUTOR so it is confustion only.
you can have Two solution for check it.
Solution : 1
print a new line after echo the $store like this
foreach ($pairs as $pair)
{
list($product,$store,$qty,$unit,$total_price,$discount,$discount_percen,$discount_value,$tax,$tax_percen,$tax_val) = explode('%*#', $pair);
echo $store;
echo "<br/>";
}
Solution : 2 save $store in array
foreach ($pairs as $pair)
{
list($product,$store,$qty,$unit,$total_price,$discount,$discount_percen,$discount_value,$tax,$tax_percen,$tax_val) = explode('%*#', $pair);
$arr_store[] = $store;
}
print_r($arr_store);

Creating array from string

I need to create array like that:
Array('firstkey' => Array('secondkey' => Array('nkey' => ...)))
From this:
firstkey.secondkey.nkey.(...)
$yourString = 'firstkey.secondkey.nkey';
// split the string into pieces
$pieces = explode('.', $yourString);
$result = array();
// $current is a reference to the array in which new elements should be added
$current = &$result;
foreach($pieces as $key){
// add an empty array to the current array
$current[ $key ] = array();
// descend into the new array
$current = &$current[ $key ];
}
//$result contains the array you want
My take on this:
<?php
$theString = "var1.var2.var3.var4";
$theArray = explode(".", $theString); // explode the string into an array, split by "."
$result = array();
$current = &$result; // $current is a reference to the array we want to put a new key into, shifting further up the tree every time we add an array.
while ($key = array_shift($theArray)){ // array_shift() removes the first element of the array, and assigns it to $key. The loop will stop as soon as there are no more items in $theArray.
$current[$key] = array(); // add the new key => value pair
$current = &$current[$key]; // set the reference point to the newly created array.
}
var_dump($result);
?>
With an array_push() in the while loop.
What do you want the value of the deepest key to be?
Try something like:
function dotToArray() {
$result = array();
$keys = explode(".", $str);
while (count($keys) > 0) {
$current = array_pop($keys);
$result = array($current=>$result);
}
return $result;
}

Categories