Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/arrays/12.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
PHP-Foreach会回显这些值,但不会将其推送到数组中_Php_Arrays_Foreach - Fatal编程技术网

PHP-Foreach会回显这些值,但不会将其推送到数组中

PHP-Foreach会回显这些值,但不会将其推送到数组中,php,arrays,foreach,Php,Arrays,Foreach,我有一个数组$x,看起来像这样: Array ( [0] => Array ( [Id] => 280123736 [BuyItNowPrice] => 600 [SellerId] => 3635925 ) [1] => Array ( [Id] => 280195277 [SellerId] => 4269145 ) [2] =>

我有一个数组$x,看起来像这样:

Array
(
[0] => Array
    (
        [Id] => 280123736
        [BuyItNowPrice] => 600
        [SellerId] => 3635925
    )

[1] => Array
    (
        [Id] => 280195277
        [SellerId] => 4269145
    )

[2] => Array
    (
        [Id] => 280195291
        [SellerId] => 4269145
     )

)
现在,我想将键为“Id”的所有值推送到一个新数组中,但我无法让它工作。我有一个递归遍历数组的函数,如下所示:

$ids = array();
function get_ids($arr) {
    if ($arr) {
        foreach ($arr as $key => $value) {
            if (is_array($value)) {
                get_ids($value);
            } else {
                if ($key == "Id") {
                    //None of these seem to work
                    //Tried them both separately of course
                    $ids[] = $value;
                    array_push($ids, $value);

                    //But printing out the values does work
                    echo "[". $key ."]: " . $value . "\n";
                }
            }
        }
    }
}
我这样调用函数:

echo "--Call get_ids() \n";
get_ids($x);

echo "--Print $ids \n";
print_r($ids);

echo "--Print $ids length \n";
count($ids);
其输出为:

--Call get_ids()
[Id]: 280123736
[Id]: 280195277
[Id]: 280195291

--Print $ids
Array
(
)

--Print $ids length 
(No output here..)
I console.log使用javascript通过AJAX调用php脚本来记录结果,如果这很重要,例如:

$.ajax ({
        url: "script.php",
        success: function(result) {
            console.log(result);
        }
});

但是,我需要在php脚本中提取“id”。有什么建议吗?

只需使用此命令将所有
Id
放入一个数组:

$ids = array_column($x, 'Id');
至于
foreach
方法,它也简单得多:

foreach($x as $value) {
    if(isset($value['Id'])) {
        $ids[] = $value['Id'];
    }           
}

为什么不仅仅是:
$ids=array_column($x,'Id')