Allie Pascoal
Allie Pascoal

Reputation: 41

How to make a associative array from other associative array?

I need some help with another PHP problem I am working on. I won't be posting the exact question, as I'd prefer to try and apply the knowledge I get from here to solve my problem.

First: I have an associative array. I must loop through the array to find the array values which have keys that begin with a specific string and push both the key and value to an output array.

eg:
- Loop through the below array & push all elements which have a key beginning with "edible_" to an output array:

$assoc_array = array(
    'edible_fruit' => 'apple',
    'animal' => 'cat',
    'edible_veg' => 'pumpkin',
    'number' => '23',
    'city' => 'Cape Town',
    'edible_berry' => 'blueberry',
    'color' => 'blue'
);

Would this work?

$result = array();

foreach ($assoc_array as $key => $value) {
    if (substr($key, 0, 7) == "edible_") {
        array_push($result, $value);
    }
}

print_r($result);

Second: How would I remove "edible_" from the output array's keys? With this second bit I have no idea where to even begin!

Third: I've managed to figure out the above with all your help, thank you! Now I just need to find out how I would print each element on a new line with a date & timestamp at the end of each line? I've got this (doesn't seem to be working):

while (list($key, $value) = each($output)) {
    print_r("$key => $value" . date("y/m/d G.i:s", time()) . "<br>");
}

Upvotes: 2

Views: 142

Answers (5)

Adrian Cid Almaguer
Adrian Cid Almaguer

Reputation: 7791

You can loop through the array and search if the key has the string that you can eliminate and make your $newArray

<?php

$assoc_array = array('edible_fruit'=>'apple', 'animal'=>'cat', 'edible_veg'=>'pumpkin', 'number'=>'23', 'city'=>'Cape Town', 'edible_berry'=>'blueberry', 'color'=>'blue');

$search = 'edible_';
$newArray = array();

#First and Second Step
foreach($assoc_array as $key => $value) {
    if(strpos($key, "edible_") === 0) {
        $newArray[substr($key, 7)] = $value;
    }
}


print_r($newArray);

echo "<br>\n";

#Third Step
foreach($newArray as $key => $value) {
    echo "$key => $value " . date("y/m/d G.i:s", time()) . "<br>\n"; 
}   

Output:

#First and Second Step
    Array ( [fruit] => apple [veg] => pumpkin [berry] => blueberry )

#Third Step    
    fruit => apple 15/04/10 3.02:16
    veg => pumpkin 15/04/10 3.02:16
    berry => blueberry 15/04/10 3.02:16

Upvotes: 1

Rizier123
Rizier123

Reputation: 59681

This should work for you:

First I remove all elements, which doesn't have edible_ at the start of the key with array_diff_ukey(). After this I simply array_combine() the elements with they keys, where I remove the prefix with array_map() and substr().

<?php

    $assoc_array = array('edible_fruit'=>'apple', 'animal'=>'cat', 'edible_veg'=>'pumpkin', 'number'=>'23', 'city'=>'Cape Town', 'edible_berry'=>'blueberry', 'color'=>'blue');

    //remove elemnts
    $result = array_diff_ukey($assoc_array, ["edible_" => ""], function($k1, $k2){
        return substr($k1, 0, 7) == $k2;
    });

    //change keys
    $result = array_combine(
                array_map(function($v){
                    return substr($v, 7);
                }, array_keys($result)),
            $result);

    print_r($result);

?>

output:

Array ( [fruit] => apple [veg] => pumpkin [berry] => blueberry )

Upvotes: 1

ksbg
ksbg

Reputation: 3284

First: yes, that would work, however I would rewrite it a bit:

foreach ($assoc_array as $key => $value) {
    if (strpos($key, 'edible_') === 0) {
        $result[] = $value;
    }
}

Regarding Second: You are asking how to remove the key from the output array. However you did not even push the key into the output array, you only pushed the value. If you'd like to also push the key, you should do it like this:

$result[$key] = $value;

But since you haven't done that, there's no need to remove the key.

If you however meant removing the edible_ part of the key from the $assoc_array, you'd just need to add a line to the loop and pass the key by reference by adding a &:

foreach ($assoc_array as &$key => $value) {
    if (strpos($key, 'edible_') === 0) {
        $key = str_replace('edible_', '', $key)
        $result[] = $value;
    }
}

Edit: As OP told me in comments, she wants to push the key without the edible part. So just do it like this:

foreach ($assoc_array as $key => $value) {
    if (strpos($key, 'edible_') === 0) {
        $key = str_replace('edible_', '', $key)
        $result[$key] = $value;
    }
}

Upvotes: 1

Marc
Marc

Reputation: 3709

This would be my approach:

foreach($assoc_array as $key => $value) {
    if(preg_match("/^edible_/",$key)) {
        $result[preg_replace("/^edible_/","",$key)] = $value;
    }
}

use preg_match to check if the key starts with what you are looking for and use preg_replace to remove the string from the beginning (^) of the key :)

Input ($assoc_array):

Array
(
    [edible_fruit] => apple
    [animal] => cat
    [edible_veg] => pumpkin
    [number] => 23
    [city] => Cape Town
    [edible_berry] => blueberry
    [color] => blue
)

Output ($result):

Array
(
    [fruit] => apple
    [veg] => pumpkin
    [berry] => blueberry
)

Upvotes: 1

Jay Blanchard
Jay Blanchard

Reputation: 34406

First of your code will work.

To remove edible_ from the key you could use explode() -

$keyParts = explode('_', $key);
$newKey = $keyParts[1];

You will have to add the new keys to the array, which you're not doing now.

foreach ($assoc_array as $key => $value) {
    if (substr($key, 0, 7) == "edible_") {
        $keyParts = explode('_', $key);
        $newKey = $keyParts[1];
        $result[$newKey] = $value;
    }
}

Upvotes: 2

Related Questions