简体   繁体   中英

PHP Key name array

I have an array $data

 fruit => apple,
 seat => sofa,

etc. I want to loop through so that each key becomes type_key[0]['value'] so eg

 type_fruit[0]['value'] => apple,
 type_seat[0]['value'] => sofa,

and what I thought would do this, namely

foreach ($data as $key => $value)
{
        # Create a new, renamed, key. 
        $array[str_replace("/(.+)/", "type_$1[0]['value']", $key)] = $value;

        # Destroy the old key/value pair
        unset($array[$key]);

}

print_r($array);

Doesn't work. How can I make it work?

Also, I want everything to be in the keys (not the values) to be lowercase: is there an easy way of doing this too? Thanks.

Do you mean you want to make the keys into separate arrays? Or did you mean to just change the keys in the same array?

    $array = array();
    foreach ($data as $key => $value)
    {
        $array['type_' . strtolower($key)] = array(array('value' => $value));
    }

if you want your keys to be separate variables, then do this:

    extract($array);

Now you will have $type_fruit and $type_sofa. You can find your values as $type_fruit[0]['value'], since we put an extra nested array in there.

Your requirements sound... suspect. Perhaps you meant something like the following:

$arr = array('fruit' => 'apple', 'seat' => 'sofa');
$newarr = array();

foreach ($arr as $key => $value)
{
  $newkey = strtolower("type_$key");
  $newarr[$newkey] = array(array('value' => $value));
}

var_dump($newarr);

First I wouldn't alter the input-array but create a new one unless you're in serious, serious trouble with your memory limit.
And then you can't simply replace the key to add a deeper nested level to an array. $x[ 'abc[def]' ] is still only referencing a top-level element, since abc[def] is parsed as one string, but you want $x['abc']['def'] .

$data = array(
 'fruit' => 'apple',
 'seat' => 'sofa'
);

$result = array();

foreach($data as $key=>$value) {
  $target = 'type_'.$key; 
  // this might be superfluous, but who knows... if you want to process more than one array this might be an issue.
  if ( !isset($result[$target]) || !is_array($result[$target]) ) {
    $result[$target] = array();
  }
  $result[$target][] = array('value'=>$value);
}

var_dump($result);

for starters

$array[str_replace("/(.+)/", "type_$1[0]['value']", $key)] = $value;

should be

$array[str_replace("/(.+)/", type_$1[0]['value'], $key)] = $value;

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