PHP create new arrays based on the values of another array - php

I have a simple PHP multi-dimension array that I'm wanting to loop through, specifically the array with the name License and add all the values item that start with the same first word to its own array (with the key set to that word).
The idea is I'd end up with something similar to this:
[desktop] => Array(
[0] => 1–3 users
[1] => 4–6 users
[2] => 7–10 users
)
[web] => Array(
[0] => 10k views/month
[1] => 25k views/month
[2] => 50k views/month
)
[app] => Array(
[0] => 5k downloads
[1] => 5k–10k downloads
[2] => 10k–25k downloads
)
This is an example of the array I'm working with $product['options']
Array
(
[0] => Array
(
[id] => 6059896471689
[product_id] => 4678842515593
[name] => Class
[position] => 1
[values] => Array
(
[0] => Regular
[1] => Oblique
[2] => Family
)
)
[1] => Array
(
[id] => 6355533201545
[product_id] => 4678842515593
[name] => License
[position] => 2
[values] => Array
(
[0] => Desktop 1–3 users
[1] => Desktop 4–6 users
[2] => Desktop 7–10 users
[3] => Desktop 11–15 users
[4] => Desktop 16–25 users
[5] => Desktop 25–50 users
[6] => Desktop 51–100 users
[7] => Desktop 101–150 users
[8] => Desktop 151–250 users
[9] => Desktop 251–400 users
[10] => Desktop 401–700 users
[11] => Desktop 701–1000 users
[12] => Desktop 1000+ users
[13] => Web 10k views/month
[14] => Web 25k views/month
[15] => Web 50k views/month
[16] => Web 100k views/month
[17] => Web 250k views/month
[18] => Web 500k views/month
[19] => Web 750k views/month
[20] => Web 1m+ views/month
[21] => App 5k downloads
[22] => App 5k–10k downloads
[23] => App 10k–25k downloads
[24] => App 25k–50k downloads
[25] => App 50–100k downloads
[26] => App 100k–250k downloads
[27] => App 250k–500k downloads
[28] => App 500k–1m downloads
[29] => App 1m+ downloads
)
)
)
And this is where I'm currently at:
foreach ($product['options'] as $option) {
if ($option['name'] == 'Style') {
$optionTitle = 'Select your fonts';
} elseif ($option['name'] == 'License') {
$optionTitle = 'Please select the type of license(s) you require';
} else {
$optionTitle = '';
}
$optionValues = array();
foreach ($option['values'] as $value) {
if ($option['name'] == 'License') {
// 3 different arrays to be added to $optionValues (desktop, web, app) HOW?
//substr(strstr($value, ' '), 1);
} else {
$optionValues[] = $value;
}
}
if ($option['name'] == 'License') {
$optionValues['desktop'] = ???;
$optionValues['web'] = ???;
$optionValues['app'] = ???;
}
$productOptions[] = array(
'name' => $option['name'],
'title' => $optionTitle,
'values' => $optionValues
);
}

To create the data split up as you want, you can just use explode() with a space, but limit it to 2 items. The first is the type and the second is the range. Then add the items to the $optionValues array using these values.
So something like ...
if ($option['name'] == 'License') {
list($type, $range) = explode(" ", $value, 2);
$optionValues[$type][] = $range;
} else {
You can also remove the following code...
if ($option['name'] == 'License') {
$optionValues['desktop'] = ???;
$optionValues['web'] = ???;
$optionValues['app'] = ???;
}

Related

Extract only email and password from text file using PHP

I have an array which have string kind of object I can say
Array
(
[0] => Name=xyz
[1] => Email=xyz43#gmail.com
[2] => Password=xyz#123
[3] => Address=xyz University Lucknow
[4] => City=xyz
[5] => Name=peter
[6] => Email=peter43#gmail.com
[7] => Password=peter#123
[8] => Address=address
[9] => City=bla
[10] => Name=Jack
[11] => Email=jack76#gmail.com
[12] => Password=jack123
[13] => Address=jackAddress
[14] => City=jackCity
)
desired output
Array
(
[Email] => xyz43#gmail.com
[Email] => peter43#gmail.com
[Email] => jack76#gmail.com
[Password] =>xyz#123
[Password] =>peter#123
[Password] =>jack123
)
Let me confess that I want this stuff for login purpose thank you in advance .
You can try like this
$stringArray = ['Name=xyz','Email=xyz43#gmail.com','Password=xyz#123','Address=xyz University Lucknow','Name=xyz','Email=xyz413#gmail.com','Password=xyz1#123','Address=xyz University Lucknow'];
$loginCredentials = [];
$i = 0;
foreach($stringArray as $item){
$data = explode('=', $item);
if(in_array('Email',$data) || in_array('Password',$data)){
$loginCredentials[$i][$data[0]] = $data[1];
if(isset($loginCredentials[$i]['Email']) && isset($loginCredentials[$i]['Password'])){
$i++;
}
}
}
//Output desired array
print_r($loginCredentials);

save path and count images in mysql database

I'm able to scan directory of files uploaded to server via FTP
Now I want to discard the empty arrays and add path and total count of images into MySQL database. I will use that path and count of images to use them in HTML player and run these pictures as video.
Here is my code:
<?php
$path = '/home/zackpc/usr/share/zoneminder/www/events/1';
// an unsorted array of dirs & files
$files_dirs = iterator_to_array( new RecursiveIteratorIterator(new RecursiveDirectoryIterator($path),RecursiveIteratorIterator::SELF_FIRST) );
echo '<html><body><pre>';
// create a new associative multi-dimensional array with dirs as keys and their files
$dirs_files = array();
foreach($files_dirs as $dir){
if(is_dir($dir) AND preg_match('/\/\.$/',$dir)){
$d = preg_replace('/\/\.$/','',$dir);
$dirs_files[$d] = array();
foreach($files_dirs as $file){
if(is_file($file) AND $d == dirname($file)){
$f = basename($file);
$dirs_files[$d][] = $f;
}
}
}
}
print_r($dirs_files);
echo '</pre></body></html>';
?>
I am getting following output:
[/home/zackpc/usr/share/zoneminder/www/events/1/18/08/06/14] => Array
(
)
[/home/zackpc/usr/share/zoneminder/www/events/1/18/08/06] => Array
(
)
[/home/zackpc/usr/share/zoneminder/www/events/1/18/08/06/11/21/28] => Array
(
[0] => 00020-capture.jpg
[1] => 00043-capture.jpg
[2] => 00006-capture.jpg
[3] => 00008-capture.jpg
[4] => 00049-capture.jpg
[5] => 00007-capture.jpg
[6] => 00013-capture.jpg
[7] => 00025-capture.jpg
[8] => 00016-capture.jpg
[9] => 00033-capture.jpg
[10] => 00051-capture.jpg
[11] => 00014-capture.jpg
[12] => 00044-capture.jpg
[13] => 00001-capture.jpg
[14] => 00035-capture.jpg
[15] => 00039-capture.jpg
[16] => 00048-capture.jpg
[17] => 00009-capture.jpg
[18] => 00022-capture.jpg
[19] => 00034-capture.jpg
[20] => 00024-capture.jpg
[21] => 00041-capture.jpg
[22] => 00002-capture.jpg
[23] => 00029-capture.jpg
[24] => 00023-capture.jpg
[25] => 00010-capture.jpg
[26] => 00038-capture.jpg
[27] => 00003-capture.jpg
[28] => 00017-capture.jpg
[29] => 00047-capture.jpg
[30] => 00015-capture.jpg
[31] => 00012-capture.jpg
[32] => 00005-capture.jpg
)
Only loop once. Only store what you need: paths and image counts.
foreach($files_dirs as $file){
if (is_file($file)) {
$d = dirname($file);
if (!isset($dirs_files[$d])) {
$dirs_files[$d] = 0;
} else {
++$dirs_files[$d];
}
}
}
I've got to say:
I got lost in your code.
I did not test my answer, so no guarantees that it is perfect.

Creating a multidimensional array tree from MySQL table in PHP

I'm trying to organize my mysql table into a multidimension php tree array.
For example, I'm trying to organize my products in a hierarchy for easy selection to narrow down the result the narrower they go in the result.
I am returned mysql rows like this:
Array
(
[1] => Amazon
[2] => Kindle Fire
[3] =>
[4] =>
[5] =>
[6] =>
[7] =>
[8] =>
[9] => 1
)
Array
(
[1] => Amazon
[2] => Kindle Fire HD
[3] => WiFi
[4] => 7"
[5] =>
[6] => 16GB
[7] =>
[8] =>
[9] => 2
)
Array
(
[1] => Amazon
[2] => Kindle Fire HD
[3] => WiFi
[4] => 7"
[5] =>
[6] => 32GB
[7] =>
[8] =>
[9] => 3
)
Array
(
[1] => Amazon
[2] => Kindle Fire HD
[3] => WiFi
[4] => 8.9"
[5] =>
[6] => 16GB
[7] =>
[8] =>
[9] => 4
)
Array
(
[1] => Amazon
[2] => Kindle Fire HD
[3] => WiFi
[4] => 8.9"
[5] =>
[6] => 32GB
[7] =>
[8] =>
[9] => 5
)
Array
(
[1] => Amazon
[2] => Kindle Fire HD
[3] => 4G LTE
[4] => 8.9"
[5] =>
[6] => 32GB
[7] =>
[8] =>
[9] => 6
)
Array
(
[1] => Amazon
[2] => Kindle Fire HD
[3] => 4G LTE
[4] => 8.9"
[5] =>
[6] => 64GB
[7] =>
[8] =>
[9] => 7
)
Array
(
[1] => Amazon
[2] => Kindle Fire HDX
[3] => Wifi
[4] => 7"
[5] =>
[6] => 16GB
[7] =>
[8] =>
[9] => 8
)
Array
(
[1] => Amazon
[2] => Kindle Fire HDX
[3] => Wifi
[4] => 7"
[5] =>
[6] => 32GB
[7] =>
[8] =>
[9] => 9
)
Array
(
[1] => Amazon
[2] => Kindle Fire HDX
[3] => Wifi
[4] => 7"
[5] =>
[6] => 64GB
[7] =>
[8] =>
[9] => 10
)
...etc
Note the last array value is the Product ID.
And I'm looking for help writing a recursive function that will result in an array that looks like:
Array(
'Amazon' => Array(
'Kindle Fire' => 1,
'Kindle Fire HD' => Array(
'WiFi' => Array(
'7"' => Array(
'16GB' => 2,
'32GB' => 3
)
'8.9"' => Array(
'16GB' => 4,
'32GB' => 5
)
)
)
)
)
I've tried something like:
while($row = mysqli_fetch_row($res)) {
$id = $row[0];
unset($row[0]);
unset($row[count($row)]);
$row[] = $id; // Moves id to last array value
for($i = 1; $i < count($row); $i++) {
if($i == 1) {
if(!array_key_exists($row[$i], $data)) {
// Insert key
$data[$row[$i]] = array();
}
}
else {
$level = $data[$row[$i-1]];
if(array_key_exists($row[$i], $level)) {
// Key exists
}
else {
// Insert key
}
}
}
}
I think your code has a good intention: using $level to hold the current depth. But at the moment this won't work, because you are copying via $level = $data[$row[$i-1]]; - instead you need to refer to it, e.g. with $level =& $data[$row[$i-1]];.
$result = array();
while ($row = mysqli_fetch_row($res)) [
$id = array_shift($row);
if (!isset($maxIterator))
$maxIterator = count($row)-1;
$current =& $result;
for ($i=0; $i<$maxIterator; $i++) {
if (empty($row[$i]))
break;
if (!array_key_exists($row[$i], $current))
$current[ $row[$i] ] = array();
$current =& $current[ $row[$i] ];
}
//for properly ended and wasn't broken out of sooner
if ($i == $maxIterator) {
if (!array_key_exists($row[$i], $current))
$current[ $row[$i] ] = 1;
else
$current[ $row[$i] ]++;
}
}
array_shift basically does, what you needed two lines for: get the first element of an array and then remove it. Then I save the result of the count in a variable, so it doesn't need to be recalculated in every iteration of the for AND while.
Also I would suggest setting $maxIterator manually. With the shown result a good default would be 5. This way all values before the 5th. will be used for nesting and the 5th itself will be used to count (in your example this is storage size).
As the for will execute $i++ after the last iteration (and then it fails the condition and hence the loop breaks), it can be used for the counting.
Personally I would overthink what exactly you are doing and maybe use a specifc structure for that. However, this code should give you a good impression how it can be solved using references.

get specific values of array not showing

This is what my array looks like :
Array (
[0] => SimpleXMLElement Object (
[key] => Array (
[0] => Track ID
[1] => Name
[2] => Artist
[3] => Album Artist
[4] => Composer
[5] => Album
[6] => Genre
[7] => Kind
[8] => Size
[9] => Total Time
[10] => Disc Number
[11] => Disc Count
[12] => Track Number
[13] => Year
[14] => Date Modified
[15] => Date Added
[16] => Bit Rate
[17] => Sample Rate
[18] => Play Count
[19] => Play Date
[20] => Play Date UTC
[21] => Artwork Count
[22] => Persistent ID
[23] => Track Type
[24] => Location
[25] => File Folder Count
[26] => Library Folder Count )
[integer] => Array (
[0] => 2056
[1] => 3732918
[2] => 230661
[3] => 1
[4] => 1
[5] => 1
[6] => 1993
[7] => 128
[8] => 44100
[9] => 3
[10] => 3439412487
[11] => 1
[12] => 5
[13] => 1 )
[string] => Array (
[0] => Eye of the Tiger
[1] => Survivor
[2] => Survivor
[3] => Frankie Sullivan/Jim Peterik
[4] => Greatest Hits
[5] => Rock
[6] => MPEG audio file
[7] => 772F0F53F195E705
[8] => File
[9] => file://localhost/Users/cameron/Music/iTunes/iTunes%20Media/Music/Survivor/Greatest%20Hits/01%20Eye%20of%20the%20Tiger.mp3 )
[date] => Array (
[0] => 2012-08-27T17:01:00Z
[1] => 2012-08-27T17:01:03Z
[2] => 2012-12-27T07:21:27Z ) )
that's 1 result, there is about 50 of them repeated.
I am trying to select the artist value in this case : Frankie Sullivan/Jim Peterik
please note: there is about 50 other results that come after this first one, so I would like to do a foreach to display all results.
any suggestions? I am stuck.this is the code I used to get these results:
$xml = simplexml_load_file('Library.xml');
$xmlx = $xml->dict->dict->dict->key;
$artist = $xmlx->xpath("//dict[key='Artist']");
echo "<pre>" . print_r($artist, true) . "</pre>";
It seems that you have an array of SimpleXMLElement,
so you can iterate over your array and use the SimpleXMLElement facilities.
Try:
foreach($yourArray as $simpleXmlElement)
{
// Retrieve the name
echo $simpleXmlElement->string[3];
}
Take a look at the documentation for more question: SimpleXMLElement
For your specific problem, assuming the key and string are synchronized, you can try:
// Loop on your array of SimpleXMLElement
foreach($yourArray as $simpleXmlElement)
{
// Initialize the position and found value
$position = 0;
$found = false;
// Loop on the sub array 'key' and search the 'Artist Album' position
foreach($simpleXmlElement->key as $index => $value)
{
if ($value == "Album Artist")
{
$found = true;
break;
}
// Not found, increment position
$position++;
}
// Retrieve the name if found the artist album key
if ($found)
echo $simpleXmlElement->string[$position];
}
As
[3] => Album Artist
will give the position 3
Then, when retrieving the string value, it will return Frankie Sullivan/Jim Peterik

PHP keeping Names after breaking urls into a multidimensional array

If you downvote my question, please be KIND enough to leave a reason
Hey guys I got a little snip that will take a structure of urls like so
// brevity
[182] => Array
(
[path] => /home-phone/troubleshooting
[name] => Troubleshooting
)
[183] => Array
(
[path] => /home-phone/troubleshooting/my-voicemail-to-e-mail-feature-is-not-working
[name] => My Voicemail to E-mail feature is not working.
)
[184] => Array
(
[path] => /home-phone/troubleshooting/when-i-receive-my-voicemail-by-e-mail-i-cannot-hear-the-message
[name] => When I receive my voicemail by e-mail, I cannot hear the message.
)
[185] => Array
(
[path] => /home-phone/troubleshooting/i-don-t-hear-a-dial-tone-when-i-pick-up-my-phone
[name] => I don't hear a dial tone when I pick up my phone.
)
[186] => Array
(
[path] => /home-phone/troubleshooting/i-moved-my-voice-adapter-and-can-no-longer-make-or-receive-calls
[name] => I moved my Voice adapter and can no longer make or receive calls.
)
[187] => Array
(
[path] => /home-phone/troubleshooting/my-call-waiting-is-not-working-since-i-forwarded-voice-to-another-line
[name] => My call waiting is not working since I forwarded Voice to another line.
)
[188] => Array
(
[path] => /home-phone/troubleshooting/i-m-unable-to-complete-transactions-on-ivr-phone-calls-like-online-banking
[name] => I'm unable to complete transactions on IVR phone calls (like online banking).
)
[189] => Array
(
[path] => /home-phone/troubleshooting/i-can-t-get-a-dial-tone-and-i-could-before
[name] => I can't get a dial tone (and I could before).
)
[190] => Array
(
[path] => /home-phone/troubleshooting/im-not-getting-my-voicemail-to-e-mail-messages
[name] => I'm not getting my Voicemail to E-mail messages.
)
[191] => Array
(
[path] => /home-phone/troubleshooting/my-caller-id-has-not-worked-since-i-forwarded-my-voice-line-to-another-phone-line
[name] => My Caller ID has not worked since I forwarded my Voice line to another phone line.
)
[192] => Array
(
[path] => /home-phone/troubleshooting/im-having-trouble-sending-andor-receiving-a-fax
[name] => I'm having trouble sending and/or receiving a FAX.
)
// brevity
And turn them into a multidim array, like this
[4] => home-phone
[home-phone] => Array
(
// brevity
[9] => troubleshooting
[troubleshooting] => Array
(
[0] => my-voicemail-to-e-mail-feature-is-not-working
[1] => when-i-receive-my-voicemail-by-e-mail-i-cannot-hear-the-message
[2] => i-don-t-hear-a-dial-tone-when-i-pick-up-my-phone
[3] => i-moved-my-voice-adapter-and-can-no-longer-make-or-receive-calls
[4] => my-call-waiting-is-not-working-since-i-forwarded-voice-to-another-line
[5] => i-m-unable-to-complete-transactions-on-ivr-phone-calls-like-online-banking
[6] => i-can-t-get-a-dial-tone-and-i-could-before
[7] => im-not-getting-my-voicemail-to-e-mail-messages
[8] => my-caller-id-has-not-worked-since-i-forwarded-my-voice-line-to-another-phone-line
[9] => im-having-trouble-sending-andor-receiving-a-fax
)
// brevity
)
Works pretty good, but I got to the end and realized I'd lost all my Names
(your can see theirs a second column for names), I left a spacer for a Name,
but for the life of me can't figure out how to get it in there now =(
Any ideas?
EDIT forgot my source code ;)
$tree = array();
foreach($indexArray as $branch) {
$limb = explode('/', $branch['path']);
$subTree = array(array_pop($limb));
foreach (array_reverse($limb) as $dir) {
$subTree = array($dir => $subTree);
}
$tree = array_merge_recursive($tree, $subTree);
}
Expected output should be
[Home Phone] => home-phone
[home-phone] => Array
(
// brevity
[Troubleshooting] => troubleshooting
[troubleshooting] => Array
(
[My Voicemail to E-mail feature is not working.] => my-voicemail-to-e-mail-feature-is-not-working
[When I receive my voicemail by e-mail, I cannot hear the message.] => when-i-receive-my-voicemail-by-e-mail-i-cannot-hear-the-message
[I don't hear a dial tone when I pick up my phone.] => i-don-t-hear-a-dial-tone-when-i-pick-up-my-phone
// etc
)
// brevity
)
Since you did not put expected output am working on assumption .. you can try :
$data = array();
$i = 0 ;
foreach ( $array as $key => $value ) {
$temp = array();
setPath($temp,dirname($value['path']) . "/$i/path", basename($value['path']));
setPath($temp, dirname($value['path']) . "/$i/name", $value['name']);
$data = array_merge_recursive($data, $temp);
$i ++;
}
echo "<pre>";
print_r($data);
Output
Array
(
[home-phone] => Array
(
[path] => troubleshooting
[name] => Troubleshooting
[troubleshooting] => Array
(
[1] => Array
(
[path] => my-voicemail-to-e-mail-feature-is-not-working
[name] => My Voicemail to E-mail feature is not working.
)
[2] => Array
(
[path] => when-i-receive-my-voicemail-by-e-mail-i-cannot-hear-the-message
[name] => When I receive my voicemail by e-mail, I cannot hear the message.
)
[3] => Array
(
[path] => i-don-t-hear-a-dial-tone-when-i-pick-up-my-phone
[name] => I don't hear a dial tone when I pick up my phone.
)
[4] => Array
(
[path] => i-moved-my-voice-adapter-and-can-no-longer-make-or-receive-calls
[name] => I moved my Voice adapter and can no longer make or receive calls.
)
[5] => Array
(
[path] => my-call-waiting-is-not-working-since-i-forwarded-voice-to-another-line
[name] => My call waiting is not working since I forwarded Voice to another line.
)
[6] => Array
(
[path] => i-m-unable-to-complete-transactions-on-ivr-phone-calls-like-online-banking
[name] => I'm unable to complete transactions on IVR phone calls (like online banking).
)
[7] => Array
(
[path] => i-can-t-get-a-dial-tone-and-i-could-before
[name] => I can't get a dial tone (and I could before).
)
[8] => Array
(
[path] => im-not-getting-my-voicemail-to-e-mail-messages
[name] => I'm not getting my Voicemail to E-mail messages.
)
[9] => Array
(
[path] => my-caller-id-has-not-worked-since-i-forwarded-my-voice-line-to-another-phone-line
[name] => My Caller ID has not worked since I forwarded my Voice line to another phone line.
)
[10] => Array
(
[path] => im-having-trouble-sending-andor-receiving-a-fax
[name] => I'm having trouble sending and/or receiving a FAX.
)
)
)
)
Function Used
function setPath(&$temp, $url, $value) {
foreach ( array_filter(explode("/", $url)) as $key ) {
$temp = &$temp[$key];
}
$temp = $value;
}

Categories