Str_replace inside mutlidimensional array - php

I have a multidimensional array as follows, which is a PHP array of shoe sizes and their conversions...
$size_array = array(
"M"=>array(
'6'=> array('uk'=>'6','eu'=>'39.5','us'=>'7'),
'6H'=> array('uk'=>'6.5','eu'=>'40','us'=>'7.5'),
'7'=> array('uk'=>'7','eu'=>'40.5','us'=>'8'),
'7H'=> array('uk'=>'7.5','eu'=>'41','us'=>'8.5'),
'8'=> array('uk'=>'8','eu'=>'42','us'=>'9'),
'8H'=> array('uk'=>'8.5','eu'=>'42.5','us'=>'9.5'),
'9'=> array('uk'=>'9','eu'=>'43','us'=>'10'),
'9H'=> array('uk'=>'9.5','eu'=>'44','us'=>'10.5'),
'10'=> array('uk'=>'10','eu'=>'44.5','us'=>'11'),
'10H'=> array('uk'=>'10.5','eu'=>'45','us'=>'11.5'),
'11'=> array('uk'=>'11','eu'=>'46','us'=>'12'),
'11H'=> array('uk'=>'11.5','eu'=>'46.5','us'=>'12.5'),
'12'=> array('uk'=>'12','eu'=>'47','us'=>'13'),
'12H'=> array('uk'=>'12.5','eu'=>'48','us'=>'13.5'),
'13'=> array('uk'=>'13','eu'=>'48.5','us'=>'14')
),
"F"=>array(
'3'=> array('uk'=>'3','eu'=>'35.5','us'=>'5'),
'3H'=> array('uk'=>'3.5','eu'=>'36','us'=>'5.5'),
'4'=> array('uk'=>'4','eu'=>'37','us'=>'6'),
'4H'=> array('uk'=>'4.5','eu'=>'37.5','us'=>'6.5'),
'5'=> array('uk'=>'5','eu'=>'38','us'=>'7'),
'5H'=> array('uk'=>'5.5','eu'=>'38.5','us'=>'7.5'),
'6'=> array('uk'=>'6','eu'=>'39','us'=>'8'),
'6H'=> array('uk'=>'6.5','eu'=>'39.5','us'=>'8.5'),
'7'=> array('uk'=>'7','eu'=>'40','us'=>'9'),
'7H'=> array('uk'=>'7.5','eu'=>'41','us'=>'9.5'),
'8'=> array('uk'=>'8','eu'=>'41.5','us'=>'10'),
'8H'=> array('uk'=>'8.5','eu'=>'42.5','us'=>'10.5'),
'9'=> array('uk'=>'9','eu'=>'43','us'=>'11'),
'9H'=> array('uk'=>'9.5','eu'=>'43.5','us'=>'11.5'),
'10'=> array('uk'=>'10','eu'=>'44','us'=>'12')
)
);
The array is part of a function that returns the conversions based on a supplied size and gender (i.e. SizeConvert('M','6') returns Array ([uk] => 6, [eu] => 39.5,[us] => 7)).
I want to extend the function to allow the passing of a value which will return the array results with any .5 values replaced with ½ (or ½) (i.e. SizeConvert('M','6','Y') returns Array ([uk] => 6, [eu] => 39½,[us] => 7))
How do I make str_replace (or a more appropriate command) iterate over the array and replace the values?
I've tried something like str_replace(".5", "&frac12", $size_array) but I guess that's not working as it's only looking at the initial array, not the sub-arrays.

You are trying to apply this to a multidimensional array without real reason. If you have your SizeConvert function ready and returning a one dimensional array, simply apply the transformation before returning the value:
function SizeConvert(/* other parameters */, bool $convertOneHalf) {
$match = ... // your code to find the match
return $convertOneHalf
? str_replace('.5', '½', $match)
: $match;
}
Based on the boolean value of the parameter that dictates whether the conversion should be applied, we either return the modified or the unmodified result through the ternary.

Do not overthink it and use a for loop to loop through all the elements in the array and use an if...else... to check for 0.5
if($array[index]=="0.5") {
$array[index]="½";
} else {
$array[index]=str_replace(".5", "½", $array[index]);
}
I coded up a simple code, it's not exactly the answer to your question but u can use the logic behind it. The code below will change all the 0.5 in the array to 1⁄2 but since u already acquire the data, there is no need to have so much nested-loop, just 1 level of the loop to loop through all ur elements in your array is enough.
<?php
$size_array = array(
"M" => array(
'6' => array(
'uk' => '6',
'eu' => '39.5',
'us' => '7'
) ,
'6H' => array(
'uk' => '6.5',
'eu' => '40',
'us' => '7.5'
) ,
'7' => array(
'uk' => '7',
'eu' => '40.5',
'us' => '8'
)
) ,
"F" => array(
'3' => array(
'uk' => '3',
'eu' => '35.5',
'us' => '5'
) ,
'3H' => array(
'uk' => '3.5',
'eu' => '36',
'us' => '5.5'
) ,
'4' => array(
'uk' => '4',
'eu' => '37',
'us' => '6'
)
)
);
foreach ($size_array as $firstLevel)
{
foreach ($firstLevel as $secondLevel)
{
foreach ($secondLevelas $values)
{
if ($values== "0.5")
{
echo $values= "½";
}
else
{
echo $values= str_replace(".5", "½", $values);
}
}
}
}
?>

Related

MAX in PHP returning wrong value

I have an array with key and value pair. I'm building this array dynamically and below is the code.
$x[] = array('type_name' => $value->name,
'percentage'=> intval($percentage));
My intention is to get the maximum value and for that I do
max($x);
However it is returning the wrong value actually the lowest value. Following is my array. Any help would be awesome.
$x = array(
array(
'type_name' => 'type 1'
'percentage' => 10,
),
array(
'type_name' => 'type 2'
'percentage' => 15,
),
array(
'type_name' => 'type 3'
'percentage' => 45,
),
);
Thanks is advance.
From php max() documentation :
// Multiple arrays of the same length are compared from left to right
It means that if you want to compare "percentage" values first instead of "type_name" values, you'll have to change their order in the array.
So, you could build your array like this ("percentage" comes first) and it should work :
$x[] = array(
'percentage'=> intval($percentage),
'type_name' => $value->name
);
For example :
$x = array(
array(
'percentage' => 10,
'type_name' => 'type 1'
),
array(
'percentage' => 15,
'type_name' => 'type 2'
),
array(
'percentage' => 45,
'type_name' => 'type 3'
),
array(
'percentage' => 25,
'type_name' => 'type 4'
)
);
print_r(max($x));
Output :
Array
(
[percentage] => 45
[type_name] => type 3
)
Hope it helps.
You need to read how the max compares against different types of data. In your case, you are trying to compare against one of the array item i.e. percentage inside one of the item so the function max does not know to do this.
There is an example by Revo in the manual which shows you how to do this.
You are creating an array of arrays. max doesn’t know that your arrays should be compared by the 'percentage' key, so it can’t be used here.
Instead, find the maximum value yourself. For example, like this:
$maxPercentage = false;
foreach ($x as $item) {
if ($maxPercentage === false || $item['percentage'] > $maxPercentage) {
$maxPercentage = $item['percentage'];
}
}
Now, $maxPercentage will store maximum percentage. Of, if you want an item with maximum percentage, get it like this:
$maxPercentage = false;
$maxItem = false;
foreach ($x as $item) {
if ($maxPercentage === false || $item['percentage'] > $maxPercentage) {
$maxPercentage = $item['percentage'];
$maxItem = $item;
}
}

Transpose an array of arrays [duplicate]

This question already has answers here:
Transposing multidimensional arrays in PHP
(12 answers)
Closed 6 months ago.
Hah, I had no idea how else to phrase that. I'm trying to reformat a set of three arrays generated by form field inputs, into something that better matches my models, so I can save the values to the db.
Not sure if the solution should be some array manipulation or that I should change the "name" attribute in my form fields.
currently I have an array of my input data:
array(
'image_id' =>
array
0 => '454' (length=3),
1 => '455' (length=3),
2 => '456' (length=3)
'title' =>
array
0 => 'title1' (length=6),
1 => 'title2' (length=0),
2 => '' (length=6)
'caption' =>
array
0 => 'caption1' (length=8),
1 => '' (length=8),
2 => 'caption3' (length=8)
);
and would like to change it to something like, so I can iterate over and save each array of values to the corresponding resource in my db.
array(
0 =>
array
'image_id' => '454',
'title' => 'title1',
'caption' => 'caption1'
1 =>
array
'image_id' => '455',
'title' => 'title2',
'caption' => ''
2 =>
array
'image_id' => '456',
'title' => '',
'caption' => 'caption3'
);
This would iterate through the array with 2 foreach loops. They would use each other's key to construct the new array, so it would work in any case:
$data = array(
'image_id' => array(454, 455, 456),
'title' => array('title1', 'title2', ''),
'caption' => array('caption1', '', 'caption3')
);
$result = array();
foreach($data as $key => $value) {
foreach ($value as $k => $v) {
$result[$k][$key] = $v;
}
}
This'll do it:
$array = call_user_func_array('array_map', array_merge(
[function () use ($array) { return array_combine(array_keys($array), func_get_args()); }],
$array
));
Assuming though that this data is originally coming from an HTML form, you can fix the data right there already:
<input name="data[0][image_id]">
<input name="data[0][title]">
<input name="data[0][caption]">
<input name="data[1][image_id]">
<input name="data[1][title]">
<input name="data[1][caption]">
Then it will get to your server in the correct format already.

need to array display in specific format in php

Capture the 'p_data' values into key/pairs and return as table
i try to array display in table format please help me.
$diskspace = array (
'S' =>
array ('DISK-FREE' =>
array (
'name' => 'S',
'desc' => 'FREE',
'p_data' => '\'C:\\ %\'=19%;99;95 \'C:\\\'=17B;3;1073741824;0;21476171776 \'D:\\ %\'=63%;99;99 \'D:\\\'=80B;3;1073741824;0;214753800192 \'E:\\ %\'=91%;99;98 \'E:\\\'=58B;3;1073741824;0;64420311040',),
),
'T' =>
array ('DISK-FREE' =>
array ('name' => 'T',
'desc' => 'FREE',
'p_data' => '\'C:\\ %\'=11%;99;95 \'C:\\\'=15B;3;1073741824;0;21476171776 \'D:\\ %\'=18%;99;99 \'D:\\\'=62B;3;1073741824;0;214753800192',),
),
'P' =>
array ('DISK-USED' =>
array ('name' => 'P',
'desc' => 'FREE',
'p_data' => '\'G:\\ %\'=19%;99;95 \'G:\\\'=92B;3;1073741824;0;21476171776',),
),
);
HTML Output
name, diskname, disk-size, disk-percentage
S, C:\, 17B, 19%
S, D:\, 80B, 63%
S, E:\, 58B, 91%
T, C:\, 15B, 11%
T, D:\, 62B, 18%
P, G:\, 92B, 19%
Use this code to extract All xxB and xx% data and try to display them drom array, make sure you try this for S , T , ... or other data in array
function Disk2Array($Name , $array) {
return $array[$Name]['DISK-FREE']['p_data'];
}
$precent = '/[0-9][0-9]\%/';
$size = '/[0-9][0-9][B]/';
preg_match_all($size , Disk2Array('S' , $diskspace) , $match);
print_r($match);
preg_match_all($precent , Disk2Array('S' , $diskspace) , $match);
print_r($match);
You have not specified what you wanted to put into the specific attributes as values and I am reluctant to guess it, so I will assume that you have a function which handles a passed p_data and returns the array you need to have.
function handlePValue($p_value) {
//your code here to return the desired value
}
$p_dataValues = array();
foreach ($diskspace as $element) {
$p_dataValues[] = handlePValue($element["p_data"]);
}

Applying a custom order to a multi-dimensional array

I have this array
$arr = array(
'one' => array(
'slidertitle' => 'lorem ipsum',
'sliderlocation' => 'http://localhost/images/1.jpg',
'sliderdescription' => 'this is a good lorem ipsum image',
'sliderposition' => 1
),
'two' => array(
'slidertitle' => 'second slider',
'sliderlocation' => 'http://localhost/images/2.jpg',
'sliderdescription' => 'this space was reserved for a link source code here',
'sliderposition' => 2
),
'six' => array(
'slidertitle' => 'sixth slider',
'sliderlocation' => 'http://localhost/images/6.jpg',
'sliderdescription' => 'this is the sixth slider,like,really!',
'sliderposition' => 6
)
);
which i need to look like this
$arr = array(
'two' => array(
'slidertitle' => 'second slider',
'sliderlocation' => 'http://localhost/images/2.jpg',
'sliderdescription' => 'this space was reserved for a link source code here',
'sliderposition' => 2
),
'six' => array(
'slidertitle' => 'sixth slider',
'sliderlocation' => 'http://localhost/images/6.jpg',
'sliderdescription' => 'this is the sixth slider,like,really!',
'sliderposition' => 6
),
'one' => array(
'slidertitle' => 'lorem ipsum',
'sliderlocation' => 'http://localhost/images/1.jpg',
'sliderdescription' => 'this is a good lorem ipsum image',
'sliderposition' => 1
)
);
I am attempting to do that by defining the expected array structure and introducing a dummy array.I then chunk the array and merge each chunk to the array format and i plan to finally unset the dummy and i am left with the array i want and in the order i want.
$arrayFormat = array(
'dummy' => array(
'slidertitle' => 'xxxx',
'sliderlocation' => 'xxxxxxx',
'sliderdescription' => 'xxxxxx',
'sliderposition' => 0
)
);
$arrayLength = count($arr);
$afterChunk = array_chunk($arr,$arrayLength);
$one = $afterChunk[0][0];
$two = $afterChunk[0][1];
$mergedArray = array_merge($arrayFormat,$one);
$secondMergedArray = array_merge($mergedArray,$two);
echo '<pre>';
print_r($secondMergedArray);
echo '</pre>';
The problem is array_chunk() does not include the key of the array so i am getting
Array (
[dummy] => Array
(
[slidertitle] => xxxx
[sliderlocation] => xxxxxxx
[sliderdescription] => xxxxxx
[sliderposition] => 0
)
[slidertitle] => second slider
[sliderlocation] => http://localhost/images/2.jpg
[sliderdescription] => this space was reserved for a link source code here
[sliderposition] => 2 )
when i print_r($secondMergedArray);.is there something that can be done to array_chunk() to include the array key or is there any other array function that can help me get individual array inclusive of the key?.
It's really hard to tell what you're wanting in terms of how to sort the elements. You've not been very clear in the question. There has to be something in the array that you know what order it needs to be.
In the absence of any clues as to what that is, I'm going to assume you want to specify the order of the array keys manually.
So, the current array is array('one'=>... , 'two'=>... , 'six'=>... ) and you want to sort those keys in an order you want to specify manually.
The solution is to use the uksort() function, along with a separate array specifying your sort order:
$arr = ... //input array as specified in the question
$sortOrder = array('two','one','six');
uksort($arr, function ($a, $b) use ($sortOrder) {
$sortMe = array_flip($sortOrder);
if ($sortMe[$a] == $sortMe[$b]) { return 0; }
return ($sortMe[$a] < $sortMe[$b]) ? -1 : 1;
});
print_r($arr);
Outputs your array in 'two','one','six' order. Change the $sortOrder array as required.
Hope that helps.
Note: the syntax I've provided above only works in PHP 5.3 and above. (if you're using an older version, you need to upgrade)
use uksort() for custom order for multidimensional array
http://php.net/manual/en/function.uksort.php

PHP - Sorting an array of data rows by price, date ASC, DESC, etc

I have an array of data which contains associative array rows and I would like to sort them by price,date etc. This cannot be done via SQL as these values are not in a database - I simply have a large array with the following example data:
$data[0] = array(
'id' => '2',
'price' => '400.00',
'date' => '2012-05-21',
),
$data[1] = array(
'id' => '4',
'price' => '660.00',
'date' => '2012-02-21',
),
$data[2] = array(
'id' => '8',
'price' => '690.00',
'date' => '2012-01-21',
)
etc..................
How can I sort this variable based on a select box such as sort by price ASC/DESC and date ASC/DESC
Sorry if this is simple - I am just so used to doing it via SQL that my mind has gone blank in this case.
I think you may modify this function:
http://php.net/manual/en/function.sort.php#104464
You should use usort and define a function which sorts based on the key you want.
Check out http://www.php.net/manual/en/function.usort.php examples 2 and 4.
Below sample code will sort it by id.
$capitals = array(
array(
'id' => '2',
'price' => '400.00',
'date' => '2012-05-21',
),
array(
'id' => '1',
'price' => '660.00',
'date' => '2012-02-21',
),
array(
'id' => '0',
'price' => '690.00',
'date' => '2012-01-21',
)
);
function cmp($a, $b)
{
return strcmp($a["id"], $b["id"]);
}
usort($capitals, "cmp");
print_r($capitals);
Use usort:
function sortBySubKey(&$array, $key)
{
return usort($array, create_function('$a,$b', 'if ($a["'.$key.'"] == $b["'.$key.'"]) return 0; return ($a["'.$key.'"] < $b["'.$key.'"]) ? -1 : 1;'));
}
You should make sure that your array holds valid values in the sense of this arithmetical comparision (<), eg. you should probably pass date as a unix timestamp for this, price as a float and so on...

Categories