문제

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