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
Related
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", "½", $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);
}
}
}
}
?>
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;
}
}
I have a question. So I have this array :
$a_list_id = array(
0 => 1234
1 => 739
3 => 538
);
And this array :
$a_users = array(
0 => array(
id => 15627,
name => test
),
1 => array(
id => 1234,
name => test1
),
2 => array(
id => 739,
name => test2
)
)
The result should be :
$a_response = array(
0 => array(
id => 1234,
name => test1
)
)
Because the id 1234 is in both arrays.
I try with array_intersect but not work. Can you help me please ?
Just use loops :
$a_response = array();
foreach ($a_users as $array) {
if (in_array($array['id'], $a_list_id)) {
$a_response []= $a_users;
}
}
array_intersect will only produce useful results if the values of both arrays can be cast to the same type. You've got an array of integers and another array of arrays, they can never* match so intersect will always be empty
If you want an intersection between the arrays then you have two options:
Index the arrays so their keys are the values you want to intersect and use array_intersect_key
Implement your own array comparison logic with array_uintersect and a callback function that knows the structure of the arrays being compared
example of the former:
$a_list_id = array(
1234 => 1234
739 => 739
538 => 538
);
$a_users = array(
15627 => array(
id => 15627,
name => test
),
1234 => array(
id => 1234,
name => test1
),
739 => array(
id => 739,
name => test2
)
)
var_dump (array_intersect_key ($a_users, $a_list_id));
Example of the latter:
var_dump (array_uintersect ($a_users, $a_list_id, function ($user, $id) {
return $user ["id"] - $id; // Result should be 0 if they match, as per documentation
}))
*They can be considered the same in the case where one value is integer 0 and the other is an empty array, but that's not very useful
Try the below code using array_search() function:
$a_list_id = array(1234, 538,739);
$a_users = array(
array(
'id'=> 15627,
'name' => 'test'
),
array(
'id' => 1234,
'name' => 'test1'
),
array(
'id' => 739,
'name' => 'test2'
)
);
foreach($a_users as $a_user){
if (in_array($a_user['id'], $a_list_id)) {
$a_response[array_search($a_user['id'], $a_list_id)] = $a_user;
}
}
print_r($a_response);
Have you tried using array_intersect_uassoc? http://php.net/manual/en/function.array-intersect-uassoc.php
function compare_ids($a, $b)
{
return $a - $b['id'];
}
print_r(array_intersect_uassoc($a_list_id, $a_users, "compare_ids"));
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.
$result = $proxy->salesOrderInvoiceCreate((object)array('sessionId' => $sessionId->result, 'itemsQty' => array('order_item_id' => 15, 'qty' => '1')));
$mainarray[];
$itemarray[];
I need multiple of this
array('order_item_id' => 15, 'qty' => '1')
Which means i need a array in a array.
foreach(statement){
array_push($itemarray, "order_item_id", echo $item->product_id;);
array_push($itemarray, "qty", echo $item->qty);
array_push($mainarray, $itemarray);
}
enter code here
Request Example SOAP V2 (WS-I Compliance Mode)
http://www.magentocommerce.com/api/soap/sales/salesOrderInvoice/sales_order_invoice.create.html
In fact i'm also not sure what do i replace the current
array('order_item_id' => 15, 'qty' => '1')
with
array($mainarray) ??
That is not the correct way of using array_push your current $itemarray output will look something like
Array
(
[0] => 'order_item_id'
[1] => '200'
[2] => 'qty'
[3] => '2'
)
I would go back to basics and use something like to generate your multi dimensional array:
$itemarray[] = array("order_item_id" => $item->product_id, "qty" => $item->qty);
array_push($mainarray, $itemarray);
Edit:
Ok I reread your questions, ignore $mainArray.
$result = $proxy->salesOrderInvoiceCreate((object)array('sessionId' => $sessionId->result, 'itemsQty' => $itemarray));
That should work as with the other examples qty/itemsQty show it accepting multikey arrays.