0

This is my current array which keep a first character from the value

Array ( [n] => Array ( [0] => name_john ) [a] => Array ( [0] => age_30 ) )

foreach ($queryArray as $key) {
    $inArray[$key[0]][] = $key;
}

Question : How do I grab a word before underscore and change the array to be like

Array
(
    [name] => Array
        (
            [0] => name_john
        )

    [age] => Array
        (
            [0] => age_30
        )

)
MRA
  • 277
  • 2
  • 9
  • 1
    Where do you get the array from? If possible you should solve the actual problem and create the array with an appropriate structure. – Felix Kling Nov 11 '11 at 17:36

5 Answers5

3

To parse out the word before the underscore, use explode:

// $key = name_john
$split_key = explode('_',$key);
// $split_key[0] equals name
Mario Lurig
  • 783
  • 1
  • 6
  • 16
1
$pieces = explode("_", $key);
echo $pieces[0];
Zoltan Toth
  • 46,981
  • 12
  • 120
  • 134
1
$inArray[$key[0]][] = substr($key, 0, strpos($key, '_'));

But if you make the array using the "key" as the assoc. index, like

Array ( [n] => Array ( ["name"] => john ) [a] => Array ( ["age"] => 30 ) )

Then you can

foreach ($queryArray as $subArr) {
    foreach($subArr as $subkey => $val){
        $inArray[$subkey][] = $val;
    }
}

and you should get an array like

Array
(
    ["name"] => "john"

    ["age"] => 30
)

Tho its not the "desired" output, might be cleaner and easier to use for what it seems like you're doing.

Nick Rolando
  • 25,879
  • 13
  • 79
  • 119
1
  • To split the value, use explode('_', $value) and get the first item of the returned array.
  • To modify an array in a foreach, add a reference on the array
  • To change a key of an element in an array, check this thread: In PHP, how do you change the key of an array element?

Working example: (codepad here)

<?php

$array = array('n' => Array(0 => 'name_john'), 'a' => Array('0' => 'age_30'));

foreach ($array as &$value) {
    foreach ($value as $oldkey => $name) {
        $chunks = explode('_', $name);
        $newkey = $chunks[0];
        // see https://stackoverflow.com/questions/240660/in-php-how-do-you-change-the-key-of-an-array-element
        $value[$newkey] = $value[$oldkey];
        unset($value[$oldkey]);
    }
}
var_dump($array);

Output:

array
  'n' => 
    array
      'name' => string 'name_john' (length=9)
  'a' => &
    array
      'age' => string 'age_30' (length=6)
Community
  • 1
  • 1
Benjamin Crouzier
  • 40,265
  • 44
  • 171
  • 236
  • It's work when have a single `name_` and getting blank if have twice `name_` example array `$array = array('n' => Array(0 => 'name_john', 1 => 'name_peter'), 'a' => Array('0' => 'age_30'));` – MRA Nov 11 '11 at 18:13
0

Try put this inside your foreach statement :)

$string = strstr($key, '_', true); 
echo $string; // prints ewverything before the '_'
Peter Stuart
  • 2,362
  • 7
  • 42
  • 73