如何在数组中创建if

时间:2014-01-17 13:23:25

标签: php arrays

    foreach( $top_9_friends as $key => $user )
{

 array_push( $scores,  array( 

  "id" => key($friends_rank_data),
  "likes" => $user['likes'],
  "comments" => $user['comments'],
  "posts" => $user['posts'],
  if(1 == 1) {
         $url = 'https://graph.facebook.com/' . key($friends_rank_data) . '/?fields=gender&access_token=' . $access_token ;
        $contents = file_get_contents( $url );
if( $contents )
{
    $dataa = json_decode( $contents, true );
}
    "sex" => $dataa['data']['0']['gender'],     
    }
 )

 );
}

谁能帮我怎么写正确的代码, 哪里错了 如何输入正确的日期

3 个答案:

答案 0 :(得分:1)

在数组之前执行if:

foreach( $top_9_friends as $key => $user )
{

    if(1 == 1) {
        $url = 'https://graph.facebook.com/' . key($friends_rank_data) . '/?fields=gender&access_token=' . $access_token ;
        $contents = file_get_contents( $url );
        if( $contents )
        {
            $dataa = json_decode( $contents, true );
        }
    }

    array_push( $scores,  array( 
        "id" => key($friends_rank_data),
        "likes" => $user['likes'],
        "comments" => $user['comments'],
        "posts" => $user['posts'],
        "sex" => $dataa['data']['0']['gender'],     
     );
 }

答案 1 :(得分:1)

尝试这样的事情。为每个新项创建一个数组,并设置您首先知道的值。然后,您可以根据if语句有条件地为其添加值。然后,一旦构建了数组项,将其添加到scores数组。

<?php

foreach( $top_9_friends as $key => $user ){

    //Temporary Array with entity proprties
    $new_array_item = array( 
        "id" => key($friends_rank_data),
        "likes" => $user['likes'],
        "comments" => $user['comments'],
        "posts" => $user['posts']
    );

    //Conditionally Add values based on IF logic
    if(1 == 1) {
        $new_array_item['url'] = 'https://graph.facebook.com/'.key($friends_rank_data).'/?fields=gender&access_token='.$access_token ;

        $contents = file_get_contents( $new_array_item['url'] );
        if( $contents ) {
            $dataa = json_decode( $contents, true );
            $new_array_item['sex'] = $dataa['data']['0']['gender'];
        }
    }
    //Tack Temporary Array Item onto $scores
    $scores[]=$new_array_item;
}

?>

答案 2 :(得分:1)

不确定您尝试尝试的是什么,只是将您如何构建阵列分开。

此外不需要如果(1 == 1){...} ,这只是意味着你总是这样做,为什么要这么麻烦呢?

foreach ($top_9_friends as $key => $user) {

    // create array
    $arr = array(
        "id" => key($friends_rank_data),
        "likes" => $user['likes'],
        "comments" => $user['comments'],
        "posts" => $user['posts']
    );

    $url = 'https://graph.facebook.com/' . key($friends_rank_data) . '/?fields=gender&access_token=' . $access_token;
    $contents = file_get_contents($url);
    if ($contents) {
        $dataa = json_decode($contents, true);

        // add this array key inside the if statement
        $arr["sex"] = $dataa['data']['0']['gender'];
    }
    array_push($scores, $arr);
}