I have the following challenging array of associative arrays in php.

    array(
            (int) 0 => array(
                    'table' => array(
                            'venue' => 'venue1',
                            'name' => 'name1'                                
                    )
            ),
            (int) 1 => array(
                    'table' => array(
                            'venue' => 'venue1',
                            'name' => 'name2'      
                    )
            ),
            (int) 2 => array(
                    'table' => array(
                            'venue' => 'venue2',
                            'name' => 'name3'      
                    )
            ),
            (int) 3 => array(
                    'table' => array(
                            'venue' => 'venue3',
                            'name' => 'name4'      
                    )
            )
    )     

I want to extract a list of relevant names out based on the venue. I would like to implement a function ExtractNameArray($venue) such that when $venue=='venue1', the returned array will look like array('name1', 'name2')

I have been cracking my head over this. I am starting with $foreach and am stuck. How can this be done in php? Thank you very much.

有帮助吗?

解决方案

first, you have to pass the array with the data to the function

second, the name of the function should start with lower character (php conventions)

try this

function extractNameArray($array, $venue) {
    $results = array();
    foreach($array as $key=>$value) {
        if(isset($value['table']['venue'])&&$value['table']['venue']==$venue) {
            isset($value['table']['name']) && $results[] = $value['table']['name'];
        }
    }
    return $results;
}

其他提示

function ExtractNameArray($venue) 
{
    $array = array(); // your array 
    $return_array = array();
    foreach($array as $arr)
    {
        foreach($arr['table'] as $table)
        {
            if($table['venue'] == $venue)
            {
                $return_array[]['name'] = $table['name'];
            }
        }
    }
    return $return_array;
}

You must define $array with you array. Good Luck

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top