开发者

PHP Key name array

开发者 https://www.devze.com 2022-12-24 08:58 出处:网络
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

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;
0

精彩评论

暂无评论...
验证码 换一张
取 消