解析错误:语法错误,意外的'foreach'(T_FOREACH),期待')'in

时间:2014-07-31 09:46:18

标签: php wordpress

我想用这种方式从数据库中编写一些关联数组。但是它会产生一些错误。 我想知道有什么缺点。

 var $example_data = array(

            foreach ( $user_query->results as $user ) {
            array(
                'ID'         => $user->ID,
                'Name'       => $user->display_name,
                'Email'      => $user->user_email,
                'Phone'      => ''
            ),}


        );

2 个答案:

答案 0 :(得分:3)

您不能将foreach编写为INSIDE数组声明。

试试这个

$example_data = array();    //initialize a valiable as an array

foreach ( $user_query->results as $user ) {
    $example_data[] =  array(
                           'ID'         => $user->ID,
                           'Name'       => $user->display_name,
                           'Email'      => $user->user_email,
                           'Phone'      => ''
                       );
}

编辑:独立测试模型,在PHP CLI中运行

<?php

// mockup the data
$user_query = new stdClass();
$t = new stdClass();
$t->ID = 1;
$t->display_name = 'aaa';
$t->user_email = 'aaa';
$user_query->results[] = $t;
$t = new stdClass();
$t->ID = 2;
$t->display_name ='bbb';
$t->user_email = 'bbb';
$user_query->results[] = $t;
//show the data
echo 'DATA Going into the foreach loop'.PHP_EOL;
print_r($user_query);


$example_data = array();    //initialize a valiable as an array

foreach ( $user_query->results as $user ) {
    $example_data[] =  array(
                           'ID'         => $user->ID,
                           'Name'       => $user->display_name,
                           'Email'      => $user->user_email,
                           'Phone'      => ''
                       );
}
// Show the result
echo 'Contents of $example_data'.PHP_EOL;
print_r($example_data);

此输出结果:

DATA Going into the foreach loop
stdClass Object
(
    [results] => Array
        (
            [0] => stdClass Object
                (
                    [ID] => 1
                    [display_name] => aaa
                    [user_email] => aaa
                )

            [1] => stdClass Object
                (
                    [ID] => 2
                    [display_name] => bbb
                    [user_email] => bbb
                )

        )

)
Contents of $example_data
Array
(
    [0] => Array
        (
            [ID] => 1
            [Name] => aaa
            [Email] => aaa
            [Phone] =>
        )

    [1] => Array
        (
            [ID] => 2
            [Name] => bbb
            [Email] => bbb
            [Phone] =>
        )

)

答案 1 :(得分:0)

您放置值的数组($ user变量)应该有一些名称,所以首先要像这样定义 - &gt;

$test_array = array();

此处test_array是该数组变量的名称,您无法使用语言关键字命名变量

foreach ( $user_query->results as $user ) {
        $test_array(
            'ID'         => $user->ID,
            'Name'       => $user->display_name,
            'Email'      => $user->user_email,
            'Phone'      => ''
        );
}