如何将foreach放入单独的变量中?

时间:2014-04-12 11:49:09

标签: php mysql sql-server

我已经在这个论坛上搜索了2天,但我似乎无法控制“foreach”的事情。

我发现了这个:

这正是我需要的,但是! 如何获得输出“echo”$ key = \“$ value \”
“;”在可重用变量???

    <?php
    /* Create Array named $profile with contents of jos_users */
    $user =& JFactory::getUser();
    foreach ($user as $key => $value)
    {
    $profile[$key] = $value;
    }

    /* Extract jos_user_profiles data and add to $profile */
    $db = JFactory::getDBO();
    $query = $db->getQuery(true);
    $query->select('profile_key, profile_value');
    $query->from('#__user_profiles');
    $query->where('user_id = '. (int) $user->id);
    $db->setQuery($query);
    $rows = $db->loadObjectList();
    foreach ($rows as $row)
    {
    $profile[$row->profile_key] = $row->profile_value;
    }

    /* Included for debugging purposes only 8*/
    foreach ($profile as $key => $value)
    {
    echo "$key = \"$value\"<br/>";
    }
    ?>

生成的输出如下:

    id = "636"
    name = "test2"
    username = "test2"
    email = "test2@test.nl"
    password = "$P$DcH9yo/xVoU7vTXgvmwCrCn5dDwfnE0"
    password_clear = ""
    block = "0"
    sendEmail = "0"
    registerDate = "2014-04-11 18:49:24"
    lastvisitDate = "2014-04-12 07:51:45"
    activation = ""
    params = "{}"
    groups = "Array"
    guest = "0"
    lastResetTime = "0000-00-00 00:00:00"
    resetCount = "0"
    _errors = "Array"
    aid = "0"
    otpKey = ""
    otep = ""
    testprofile.phonenumber = "523657543763"

我想要的是输出变量,例如“id =”636“”变为$ id =“636”,或$ variablename =“636”

有没有办法可以从上面的代码中生成/声明自动变量? (并列出它们,所以我可以看到声明了哪些变量)。

我想做的是:

从$ user获取数据并重用该数据,通过以下代码将更改的mysql数据插入/更新到MsSQL数据库中:

    include ('includes/connectwk.php');

    $sql = "select DEEL_ID, DEEL_TEAM, DEEL_NAAM, DEEL_TELEFOON, DEEL_MAIL from         WK_DEELNEMERS where DEEL_ID = '$usr_id'";
    $stmt = sqlsrv_query( $conn, $sql );

    if( $stmt === false)
    {
    die( print_r( sqlsrv_errors(), true) );
    echo 'connection failed!';
    }

    //script part
    if ($usr_id === 0 or $usr_login === null)
    {}
    else
    {
    if (sqlsrv_has_rows($stmt))
    {
    while( $row = sqlsrv_fetch_array( $stmt, SQLSRV_FETCH_ASSOC))
    {
        $c_id   =   $row['DEEL_ID'];
        $c_team =   $row['DEEL_TEAM'];
        $c_naam =   $row['DEEL_NAAM'];
        $c_tel  =   $row['DEEL_TELEFOON'];
        $c_mail =   $row['DEEL_MAIL'];

        if ($usr_id === $c_id and $usr_login === $c_team and $usr_mail === $c_mail and $row['DEEL_NAAM'] === $usr_name)
        {
        $update = false;
        }
        else
        {
        $update = true;
        }
    }
}
else
{
$sql = "insert into WK_DEELNEMERS (DEEL_ID, DEEL_TEAM, DEEL_NAAM, DEEL_TELEFOON, DEEL_MAIL) values ('$usr_id','$usr_login','$usr_name','','$usr_mail')";
$stmt = sqlsrv_query( $conn, $sql );
echo 'insert uitgevoerd';
}
if ($update === true)
{
    $sql ="update WK_DEELNEMERS set DEEL_TEAM = '$usr_login',DEEL_NAAM = '$usr_name',DEEL_TELEFOON ='bla3',DEEL_MAIL= '$usr_mail' where DEEL_ID = '$usr_id '"; 
    $stmt = sqlsrv_query( $conn, $sql );
}

    }
    ?>

可能这不是这样做的方法,但在我学习的时候,请随意“推动”我朝着正确的方向前进。 :)

简而言之,我要完成的是从mssql prefix_user表和prefix_user_profiles表中获取数据。

将这些结果与我从MsSQL表中获得的结果进行比较,如果用户通过网站更新/更改了他的个人资料,则插入/更新MsSQL表。

我希望有人可以帮助我。

提前致谢:)

好的,当我这样做时:

    <?php
    $profile["id"] = "636";
    $profile["name"] = "test2";
    $profile["username"] = "test2";
    $profile["email"] = "test2@test.nl";
    $profile["password"] = "$P$DcH9yo/xVoU7vTXgvmwCrCn5dDwfnE0";
    $profile["password_clear"] = "";
    $profile["block"] = "0";

    foreach ($profile as $key => $value)
    {
      $$key = $value;
    } 

    echo $id;

    ?>

我得到:636(我想要的)

但是当我这样做时:

    <?php
    /* Create Array named $profile with contents of jos_users */
    $user =& JFactory::getUser();
    foreach ($user as $key => $value)
    {
    $$key = $value;
    }

    ?>

我得到一个空白页面。我的意思是,我用空白页面从Joomla文章运行这个php,整个模板在浏览器中显示为空白。不是因为我没有在第二个剧本中使用回声。

我不明白:/

@HüseyinBABAL这里是var_dump($ user);

    object(JUser)#35 (26) { ["isRoot":protected]=> bool(false) ["id"]=> string(3) "636" ["name"]=> string(5) "test2" ["username"]=> string(5) "test2" ["email"]=> string(13) "test2@test.nl" ["password"]=> string(34) "$P$DcH9yo/xVoU7vTXgvmwCrCn5dDwfnE0" ["password_clear"]=> string(0) "" ["block"]=> string(1) "0" ["sendEmail"]=> string(1) "0" ["registerDate"]=> string(19) "2014-04-11 18:49:24" ["lastvisitDate"]=> string(19) "2014-04-12 13:38:55" ["activation"]=> string(0) "" ["params"]=> string(2) "{}" ["groups"]=> array(1) { [2]=> string(1) "2" } ["guest"]=> int(0) ["lastResetTime"]=> string(19) "0000-00-00 00:00:00" ["resetCount"]=> string(1) "0" ["_params":protected]=> object(JRegistry)#36 (1) { ["data":protected]=> object(stdClass)#37 (0) { } } ["_authGroups":protected]=> array(2) { [0]=> int(1) [1]=> int(2) } ["_authLevels":protected]=> array(3) { [0]=> int(1) [1]=> int(1) [2]=> int(2) } ["_authActions":protected]=> NULL ["_errorMsg":protected]=> NULL ["_errors":protected]=> array(0) { } ["aid"]=> int(0) ["otpKey"]=> string(0) "" ["otep"]=> string(0) "" } 

@HüseyinBABAL这里是var_export($ user);谢谢:))

    JUser::__set_state(array( 'isRoot' => false, 'id' => '636', 'name' => 'test2', 'username' => 'test2', 'email' => 'test2@test.nl', 'password' => '$P$DcH9yo/xVoU7vTXgvmwCrCn5dDwfnE0', 'password_clear' => '', 'block' => '0', 'sendEmail' => '0', 'registerDate' => '2014-04-11 18:49:24', 'lastvisitDate' => '2014-04-12 17:27:36', 'activation' => '', 'params' => '{}', 'groups' => array ( 2 => '2', ), 'guest' => 0, 'lastResetTime' => '0000-00-00 00:00:00', 'resetCount' => '0', '_params' => JRegistry::__set_state(array( 'data' => stdClass::__set_state(array( )), )), '_authGroups' => array ( 0 => 1, 1 => 2, ), '_authLevels' => array ( 0 => 1, 1 => 1, 2 => 2, ), '_authActions' => NULL, '_errorMsg' => NULL, '_errors' => array ( ), 'aid' => 0, 'otpKey' => '', 'otep' => '', )) 

@HüseyinBABAL,这里是var_dump的输出(get_object_vars($ user));

    array(20) { ["id"]=> string(3) "636" ["name"]=> string(5) "test2" ["username"]=> string(5) "test2" ["email"]=> string(13) "test2@test.nlDit e-mailadres wordt beveiligd tegen spambots. JavaScript dient ingeschakeld te zijn om het te bekijken. " ["password"]=> string(34) "$P$DcH9yo/xVoU7vTXgvmwCrCn5dDwfnE0" ["password_clear"]=> string(0) "" ["block"]=> string(1) "0" ["sendEmail"]=> string(1) "0" ["registerDate"]=> string(19) "2014-04-11 18:49:24" ["lastvisitDate"]=> string(19) "2014-04-12 17:50:44" ["activation"]=> string(0) "" ["params"]=> string(2) "{}" ["groups"]=> array(1) { [2]=> string(1) "2" } ["guest"]=> int(0) ["lastResetTime"]=> string(19) "0000-00-00 00:00:00" ["resetCount"]=> string(1) "0" ["_errors"]=> array(0) { } ["aid"]=> int(0) ["otpKey"]=> string(0) "" ["otep"]=> string(0) "" } 

我必须提到的是使用这个脚本:

    <?php
    $user =& JFactory::getUser();
    $userArr = (array) $user;
    foreach($userArr as $key => $value) 
    {
    $$key = "$value";
    }
    echo $id;
    ?>

它抛出一个:500内部服务器错误?

我刚刚为Joomla安装了full_ajax插件后收到了这条弹出消息。

好吧,现在我试过了(希望我做得正确)

    <?php
    $user =& JFactory::getUser();
    $userArr = get_object_vars($user);
    foreach($userArr as $key => $value)
    {
    $$key = $value;
    }
    echo $id;
    ?>

仍有500个内部服务器错误。如果我把回声拿出来没关系。

3 个答案:

答案 0 :(得分:0)

您可以使用variable variables之类的;

......    
foreach ($profile as $key => $value)
{
    echo "$$key = \"$value\";\n";
}

以下是一个有效的演示: Demo

编辑:您正在尝试迭代对象。您可以使用get_object_vars来获取对象属性;

$userArr = get_object_vars($user);
foreach($userArr as $key => $value) {....

答案 1 :(得分:0)

PHP拥有一个名为array function的有用extract()来完全按照您的意愿行事。它将数组的元素拉入当前符号表(本身就是封面下的数组)。

...   
foreach ($resultset as $row)  {
    extract( $row, EXTR_OVERWRITE, 'row_');

    /*now your row elements are in the symbol table with names starting with row_ */

    echo "id = $row_id";
    echo "name = $row_name";
}

答案 2 :(得分:0)

我改变了完整的方法并创建了这个:(对我有用,可能不是最好的解决方案,但就像我说的,它有效并且我还在学习PHP)

    <?php
    session_start();
    $user =& JFactory::getUser();
    $session = JFactory::getSession(); //get cuurent session
    $session->set('user', new JUser($user->id)); //update changed profile settings
    //new data for your user after the update
    $user = JFactory::getUser();

    $usr_id     = $user->get('id');
    $usr_login  = $user->get('username');
    $usr_name   = $user->get('name');
    $usr_mail   = $user->get('email');
    $guest      = $user->guest;

    /*
    echo $guest;
    echo $usr_id;
    echo $usr_login;
    echo $usr_name;
    echo $usr_mail;
    */

// init Joomla Framework
    if ($guest === 0)
    {
        define( 'DS', DIRECTORY_SEPARATOR );

        require_once ( JPATH_BASE .DS.'includes'.DS.'defines.php' );
        require_once ( JPATH_BASE .DS.'includes'.DS.'framework.php' );

        $mainframe = JFactory::getApplication('site');

        // DBQuery
        $database =& JFactory::getDBO();
        $query = "SELECT profile_value FROM #__user_profiles WHERE user_id = '$user->id' AND profile_key LIKE 'testprofile.%'";
        $database->setQuery($query);
        $telnr = $database->loadResult();

       print_r($telnr);


    echo '<br/>';
    echo 'my id is '.$usr_id.' and username is '.$usr_login.' and phonenumber '.$telnr;

&GT;

这给了我需要的结果。

感谢所有帮助:)