PHP form array notation, reversed?

So, I have this form that is rather complicated, and the form fields are named to comply with PHP array notation, as such:

<input name='service[123][info]' value=''>

And this of course works as intended and I get the array in $_POST, which I sanitize and then keep in $in. But now I want to reverse-engineer this, when I am iterating over the form again, I have this in $in:

array(
  123 => array(
    "info" => "foo"
  )
)

And when I come to any given form field, I know that the field name is "service[123][info]" but how do I find "foo" in the sent array? Basically, I want to set the value="" parameter in the input when I have data for this field, and the data is kept in the $in array but the only reference to the data I have is the string "service[123][info]". Should I use regexp to parse that string? Sounds inflexible.

Basically, I would like something like:

$name = "service[123][info]";    
$value = form_array_lookup($name, $in);

That sets $value to the correct value from $in as referenced by $name. I hope I am making myself clear. Thanks for any comment.

Answers


This is a very case-specific (and therefore, not very desirable) example, but the general idea is to use only one delimiter between items, explode the string, and then loop through the result, checking if each item index exists.

function parse_array_path( $string,array $subject ){
    // remove ending brackets
    $string = str_replace( "]","",$string );
    // "[" is now the sole delimiter
    $part = explode( "[",$string );
    // loop and check for each index in subject array
    $i = reset( $part );
    do{
        if( ! isset( $subject[$i] ) ){
            return null;
        }
        $subject = $subject[$i];
    }
    while( $i = next( $part ) );
    return $subject;
}

example usage:

<?php
$a = array(
    "service"=>array(
        123=>array(
            "info"=>"hello, world"
        )
    )
);
$s = "service[123][info]";
print parse_array_path( $s,$a ); // "hello, world"

Use a 'foreach' to loop through the array and you can reassign the keys or values in any order you wish.

foreach ($in AS $in_key => $in_val) {

    foreach ($in_val AS $in_val_key => $in_val_val) {

        // ASSIGN VALUES TO A NEW ARRAY IF YOU WISH
        // YOU NOW HAVE $in_key, $in_val_key, $in_val_val
        // THAT YOU CAN WORK WITH AND ASSIGN
        $array[$in_val_val] = $in_val_key; // OR WHATEVER

    }

}

Need Your Help

Progress from Upload via Post

android http upload progress-bar

i want to send text, pics etc via POST to a Server. Usually i used ASynchHTTPClient a class, which i found in web ( https://github.com/AsyncHttpClient/async-http-client ).

Combining 2 sql fields in select query

php mysql sql

i am having a bit of a problem with figuring out how to structure my sql query