Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations strongm on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

manipulate array based on substring

Status
Not open for further replies.

HowieG

Programmer
Oct 12, 2001
64
CA
This is difficult to explain, so I'll give an example. I have the following array of file names:

Array
(
[38] => CP.W.CC.0805
[39] => CP.W.CC.0812
[42] => CP.W.S.0805
[43] => CP.W.S.0812
[66] => IP.W.CC.0805
[67] => IP.W.CC.0812
[70] => IP.W.SP.0805
[71] => IP.W.SP.0812
[84] => MV.W.CC.0805
[85] => MV.W.CC.0812
[88] => MV.W.RCC.0805
[89] => MV.W.RCC.0812
[90] => MV.W.RS.0805
[91] => MV.W.RS.0812
[92] => MV.W.SP.0805
[93] => MV.W.SP.0812
[96] => NG.W.IN.0805
[97] => NG.W.IN.0812
)

And I'd like to turn it into:

Array
(
[0805] => Array
(
[38] => CP.W.CC.0805
[42] => CP.W.S.0805
[66] => IP.W.CC.0805
[70] => IP.W.SP.0805
[84] => MV.W.CC.0805
[88] => MV.W.RCC.0805
[90] => MV.W.RS.0805
[92] => MV.W.SP.0805
[96] => NG.W.IN.0805
)

[0812] => Array
(
[39] => CP.W.CC.0812
[43] => CP.W.S.0812
[67] => IP.W.CC.0812
[71] => IP.W.SP.0812
[85] => MV.W.CC.0812
[89] => MV.W.RCC.0812
[91] => MV.W.RS.0812
[93] => MV.W.SP.0812
[97] => NG.W.IN.0812
)

)

Note that the keys for the first-level array are the last four characters of the item (eg. substr($a, -4)).

I don't care about the keys themselves (other than the first-level array that I want to create)

Andy bright ideas?
 
Code:
$filenamearray = //your array of filenames

foreach ($filenamearray as $key=>$filename){
 $newKey = substr($filename, -1, 4);
 $newArray[$newKey][$key] = $filename;
}
//output the array
echo "<pre>".print_r($newArray,true);
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top