简体   繁体   中英

PHP, Multi Dimensional Array, Find a Key and Return Value from an Array

Ok so I have tried to search around and have been working on this for 48 hours and I am stuck to the point of headache, would very much appreciate some assistance with where I am going wrong.

So for my use case I have a Wordpress site and I am trying to programmatically set default tags for a post based on a csv list that I upload into the backend and convert to an Array. I need to be able to search for a specific field when the page loads inside of the array, and then pull out a key value to feed into the wp_set_post_tags() argument. Here is what I have so far:

    $sku_file_upload = get_field( 'sku_file_upload', 'option' );
$skufileurl = $sku_file_upload['url'];
$skulist = array();
$term_name = get_field('mold_sku');
$rows = file($skufileurl);
$header = array_shift($rows); //get the header out
$header = explode(",", $header);
$final_array = array();

foreach ($rows as $row) {
    $row = explode(",", $row);
    $header[3] = str_replace(array("\r\n", "\n\r", "\n", "\r"), '', $header[3]);
    $row[3] = str_replace(array("\r\n", "\n\r", "\n", "\r"), '', $row[3]);
    $row[3] = str_replace(array("|"), ',', $row[3]);
    $final_array[] = array($header[0] => $row[0], $header[1] => $row[1], $header[2] => $row[2], $header[3] => $row[3]);
}

This works completely as expected and provides me with the following array (41 values, cut down for viewing here):

(
    [0] => Array
        (
            [Mold SKU] => 12MM-SM-SQ
            [Title] => 12mm Squares
            [Category] => Earings|Earings > Fishhooks
            [Tags] => square ,
        )

    [1] => Array
        (
            [Mold SKU] => 12MM-SQ-HOLLOW-DROP
            [Title] => Square Hollow Drop Studs
            [Category] => Earings|Earings > Studs
            [Tags] => square ,
        )

)

As a complete aside, I had considered revising the code as such to provide another way of searching, but can't figure out how to make it work but will show this version as well. Only change is to the final foreach loop above to provide value I am looking for on each post in the associative array name:

foreach ($rows as $row) {
    $row = explode(",", $row);
    $header[3] = str_replace(array("\r\n", "\n\r", "\n", "\r"), '', $header[3]);
    $row[3] = str_replace(array("\r\n", "\n\r", "\n", "\r"), '', $row[3]);
    $row[3] = str_replace(array("|"), ',', $row[3]);
    $final_array[$row[0]] = array($header[1] => $row[1], $header[2] => $row[2], $header[3] => $row[3]);
}

Which would give me the following:

Array
(
    [12MM-SM-SQ] => Array
        (
            [Title] => 12mm Squares
            [Category] => Earings|Earings > Fishhooks
            [Tags] => square ,
        )

    [12MM-SQ-HOLLOW-DROP] => Array
        (
            [Title] => Square Hollow Drop Studs
            [Category] => Earings|Earings > Studs
            [Tags] => square ,
        )
)

But I digress, just wanted to offer that in case it offers a better way of tackling the issue. So after I have this I then execute the following code on a pageload to see if things are working:

foreach ($final_array as $value){

    echo '<pre>';
    print_r($value['Mold SKU']);
    echo '</pre>';

Disappointingly, I get a ton of blank rows but this is not the case if I replace the print_r with any of the other keys ("Title" or "Category" or "Tags" in my first example obviously).

I am wondering what is going on and if it has something to do with the - in my key? I don't believe so because I took that out and still had the same results.

I could never get past this stage, but here is what I would ideally like to do:

I have a custom field in the back end of every page that is "mold_sku" and I want to have that value be what I search for in the array. So for example the SKU on the current page might be "12MM-SQ-HOLLOW-DROP" and I want to look through the $final_array that I created, find that value, and then I need to pull the "Tags" values and insert them into the wp_set_post_tags() argument. Here is how I envision it going:

  1. Loop through the array and find the sub array that contains the value I need by searching with $term_name that is defined as $term_name = get_field('mold_sku');and feed that into $mold_sku.

  2. Use that variable to execute:

wp_set_post_tags($post_id, $tags, true);

I am not going to put all the variations of forloops I have tried in here because it wouldn't make things any more clear (at least I don't think so) and this is already clear as mud I feel.

Appreciate any help that can be provided to point me in the right direction.

EDIT

Maybe a better way to go about this is to search for the array with the information I need in a multidimensional array and have that array of values returned so I can manipulate it?

CSV for reference

Mold SKU,Title,Category,Tags
12MM-SM-SQ,12mm Squares,Earings|Earings > Fishhooks,square |
12MM-SQ-HOLLOW-DROP,Square Hollow Drop Studs,Earings|Earings > Studs,square |
12MM-SQ-O-CUTOUT,Square O Cutouts,Earings|Earings > Fishhooks,square | o | 
13MM-CIRCLES,13mm Circles,Earings|Earings > Fishhooks,circle |
14MM-SS-STUD,Studs,Earings|Earings > Studs,metal|stainless-steel |
14MM-TRI,Triangles,Earings|Earings > Fishhooks,triangle |
16MM-SS-CIRCLES,Stainless Steel Circles,Earings|Earings > Fishhooks,metal|stainless-steel | 
17MM-BBALL-DIAMONDS,17mm Baseball Diamonds,Earings|Earings > Fishhooks,baseball-diamond|
17MM-BBALL-DIAMOND-STUD,17mm Baseball Diamond Studs,Earings|Earings > Studs,baseball-diamond|
17MM-ROUND-CROSS,Rounded Cross,Earings|Earings > Fishhooks,round-cross |
18MM-DROPS,Drops,Earings|Earings > Fishhooks,drop|
18MM-STAR,Gold Stars,Earings|Earings > Fishhooks,star | 
19MM-OVAL,Ovals,Earings|Earings > Fishhooks,oval|
20MM-CIRCLES,Circles,Earings|Earings > Fishhooks,circle|
25MM-CIR-CUT,25mm Circle Cutouts,Earings|Earings > Fishhooks,circle | 
26MM-RECT-BAR,26mm Rectangle Bars,Earings|Earings > Fishhooks,rectangle-bars|
28MM-SQ-HOLLOW,Hollow Squares,Earings|Earings > Fishhooks,square | 
30MM-LEAVES,Leaves,Earings|Earings > Fishhooks,leaf|
33MM-SKIMBOARD,Skimboards,Earings|Earings > Fishhooks,skim-board | 
36MM-LONG-TRI,Long Triangles,Earings|Earings > Fishhooks,triangle | 
38MM-DIAMOND,Diamonds,Earings|Earings > Fishhooks,diamond | 
38MM-DIAMOND-CUT,Diamond Cutouts,Earings|Earings > Fishhooks,diamond |
39MM-PENTAKINDAGON,Pentakindagon,Earings|Earings > Fishhooks,pentagon | 
40MM-CIR-CUTOUT,Circle Cutouts,Earings|Earings > Fishhooks,circle|
56MM-SQ-WIN,Square Windows,Earings|Earings > Fishhooks,square | 
9MMCIR-19MMOVAL-STUD,Circle Oval Studs,Earings|Earings > Studs,oval|
CIR-CAPSULE-CUT-STUD,Circle Capsule Cutouts,Earings|Earings > Fishhooks,capsule|circle | 
CIRCLE-SQ-STUD,Circle Hollow Square Studs,Earings|Earings > Studs,square|
CIR-CUT-SQ-CUT,Circle Squares,Earings|Earings > Fishhooks,circle|square | 
CIR-SQ-CUT-STUD,Circle Square Cutout Studs,Earings|Earings > Studs,circle|square | 
HOLLOW-DROP,Hollow Drops,Earings|Earings > Fishhooks,drop|
SQ-CUT-STUD,Square Cutout Studs,Earings|Earings > Studs,square | 
SS-PRISM,Hollow Prisms,Earings|Earings > Fishhooks,metal|stainless-steel | 
TRI-STUD,Triangles,Earings|Earings > Fishhooks,triangle | 
OBTUSE-TRI,Obtuse Triangle,Earings | Earings > Fishhooks,triangle | 
CIR-SIDE-SQ-CUTOUT,Circle Side Square Cutout Studs,Earings|Earings > Studs,circle | square | 
CIR-CLOUD,Circle Cloud Studs,Earings|Earings > Studs,circle | cloud | 
LINK-CHEVRON,Link Chevrons,Earings | Earings > Fishhooks,chevron | link | 
DIAMOND-CHEVRON,Diamond Chevrons,Earings | Earings > Fishhooks,chevron | diamond | 
9MM-CIR,9mm Circles,Earings | Earings > Fishhooks,circle | 
11MM-CIR,11mm Circle Studs,Earings|Earings > Studs,circle | 
ini_set('auto_detect_line_endings', true);

$fp = fopen($skufileurl, 'r');
$termName = 'Example SKU';

$csvHeader = fgetcsv($fp);
while ($csvRow = fgetcsv($fp)) {
    $keyedCsvRow = array_combine($csvHeader, $csvRow);

    if ($keyedCsvRow['Mold SKU'] === $termName) {
        $keyedCsvRow['Category'] = explode('|', $keyedCsvRow['Category']);
        $keyedCsvRow['Tags'] = explode('|', $keyedCsvRow['Tags']);
        
        $finalArray = $keyedCsvRow;
        break;
    }
}

fclose($fp);

Working example .

references

  • fopen - get filepointer
  • fgetcsv - parse line as csv, return as array
  • array_combine - use first array as keys, and second as values

additional information

  • wp_set_post_tags accepts tags as array, so you can pass them as they are $finalArray['Tags']
  • Have a look at JSON ( json_encode and json_decode ). Its a better format for saving your sku-file. Will replace csv. Arrays in arrays will be a no-brainer.

What your question should have looked like

Title: Parse and filter data from csv-file

Hi, im trying to read Tags of a csv-file, which looks like this:

// example data of csv file (with header!)

I need to get all Tags for a given $term_name which has to match Mold SKU . This is what i tried.

// code attempt (+optionally comment where you got stuck)

Help is much appreciated:)

Happy coding:)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM