heavyEddie Posted November 22, 2006 Share Posted November 22, 2006 I have a 3rd party class that is returning some information in the form of an array. So far so good. I would like to combing these into a single array but am having some issues figuring out the logic. I may have been looking at this to long.My array looks like this...[code]$data = array('item_number1' => 4455, 'item_qty1' => 44, 'item_number2' => 8523, 'item_qty2 => 66);[/code]I would like to convert this array so the itemnumbers become the key and the quantities become the value. Like this...[code]$data = array(4455 => 44, 8523 => 66);[/code]If piddled with foreach and while statements... just not getting the pieces together. Quote Link to comment Share on other sites More sharing options...
hitman6003 Posted November 22, 2006 Share Posted November 22, 2006 If the values will always be paired like that (itm1, quan1, itm2, quan2, etc) then you could use something like this:[code]for ($x = 0; $x < count($array); $x + 2) { $data[$array[$x]] = $array[$x + 1];}[/code]But if the values are ever in a different order, it wouldn't work. It would also be inaccurate if there were an odd number of array elements...for example if an item with a quantity of 0 didn't create an array element. Quote Link to comment Share on other sites More sharing options...
heavyEddie Posted November 22, 2006 Author Share Posted November 22, 2006 Unfortunately, the array contains many different elements and in no particular order. However, itm1 and quan1 will always go together. Quote Link to comment Share on other sites More sharing options...
hitman6003 Posted November 22, 2006 Share Posted November 22, 2006 if the keys always have the same text at the beginning..."item number" and "item qty", then this would work:[code]foreach ($array as $key => $value) { if (substr($key, 0, 11) == "item number") { $data[substr($key, 11, strlen($key)]['item_number'] = $value); } else if (substr($key, 0, 8) == "item qty") { $data[substr($key, 8, strlen($key)]['item_qty'] = $value; }}[/code]Which will generate an mulidimensional array that you can use however you like. Quote Link to comment Share on other sites More sharing options...
heavyEddie Posted November 22, 2006 Author Share Posted November 22, 2006 Very good! I will give it a try first thing in the morning. Thanks for taking the time to help. Quote Link to comment Share on other sites More sharing options...
Recommended Posts
Join the conversation
You can post now and register later. If you have an account, sign in now to post with your account.