Jump to content

Searching / Parsing an array key


heavyEddie

Recommended Posts

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.
Link to comment
Share on other sites

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.
Link to comment
Share on other sites

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.
Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.