Reuben Gomes
Reuben Gomes

Reputation: 878

PHP assoiative Array with almost Similar Keys

I have an associative array

array(
    'item_name1' => 'PCC',
    'item_name2' => 'ext',
    'item_number1' => '060716113223-13555',
    'item_number2' => '49101220160607-25222)',
)

What i Want to do is catch all the array keys where the key name has similarities

for example i want to echo out item_name (it should get both item_name1 & item_name2) but i require it in a loop (foreach/for) so that i can send within the loop the details to my database for each set of values

Thanks For the help

Upvotes: 0

Views: 64

Answers (3)

Álvaro González
Álvaro González

Reputation: 146460

Your data model seems to use numeric suffixes as a replacement for arrays so I'll assume that key name has similarities is an overestimated problem statement and you merely want to fix that.

The obvious tool is regular expressions:

$original_data = array(
    'item_name1' => 'PCC',
    'item_name2' => 'ext',
    'item_number1' => '060716113223-13555',
    'item_number2' => '49101220160607-25222)',
);

$redacted_data = array();
foreach ($original_data as $key => $row) {
    if (preg_match('/^(.+)(\d+)$/u', $key, $matches)) {
        $redacted_data[$matches[1]][$matches[2]] = $row;
    } else {
        $redacted_data[$key][] = $row;
    }
}
var_dump($redacted_data);

It should be easy to tweak for your exact needs.

I can't figure out what the i require it in a loop (foreach/for) requirement means but you can loop the resulting array as any other array:

foreach ($redacted_data as $k => $v) {
    foreach ($v as $kk => $vv) {
        printf("(%s,%s) = %s\n", $k, $kk, $vv);
    }
}

Upvotes: 0

JRsz
JRsz

Reputation: 2941

Use the funtion array_keys

$allKeys = array_keys($yourArray);
$amountKeys = count($allKeys);

Unless you do not provide more code this will give you all the keys of $yourArray Reference - array_keys

To get all the similar keys you can use this function similar-text()

Since I do not know how "similar" a key can be I would suggest you to test out different values and find a degree that matches your expectations.

Upvotes: 1

Naisa purushotham
Naisa purushotham

Reputation: 913

<?php

$items=[];
$itemsNumbers=[];
foreach($itemarr as $key=> $val)
{
    $itempos = strpos("item_name", $key);
    if ($pos !== false) 
        $items[]=$val;
    $numberpos = strpos("item_number", $key);
    if ($numberpos !== false) 
        $itemsNumbers[]=$val;

}

?>
Note: here $itemarr is your input array

$items you will get list of item names and $itemsNumbers you will get list of itemsNumbers

Upvotes: 0

Related Questions