【问题标题】:get array value from array in php从php中的数组获取数组值
【发布时间】:2015-10-21 20:04:27
【问题描述】:

我在数组中有一个数组,我想从那里获取 user_id 来设置条件。我已经尝试了一切,没有成功。请帮忙。提前致谢

<?php $post_user_obj = array('PostLike' => $post['PostLikesArray']); ?>

Array
(
[PostLike] => Array
    (
        [0] => Array
            (
                [user_id] => 47
                [post_id] => 109
            )

        [1] => Array
            (
                [user_id] => 62
                [post_id] => 109
            )

    )

 )


<?php if((array_search($id, array_column($post_user_obj, 'user_id')))): ?> 

<?php if(($id == $post_user_obj['PostLike']['user_id'])): ?> 

【问题讨论】:

  • 两个 user_id 或只是一个基于某事或?

标签: php cakephp-1.3


【解决方案1】:

您需要引用父数组索引。如:

$id = $post_user_obj['Postlike'][0]['user_id'];

或者全部列出来

foreach ($post_user_obj['PostLike'] as $this_user){
    $id = $this_user['user_id'];
}

【讨论】:

  • 感谢您的回复,如果是这种情况,那么我需要为 ids 创建数组,因为我想匹配 来自“ids”数组的 ID。有什么线索吗?
【解决方案2】:

其中包含数组的数组称为多维数组。

您可以使用foreach 遍历数组。然后使用另一个 foreach 再次循环遍历子数组。示例:

$PostLike = array(array('user_id' => 47, 'post_id' => 109), array('user_id' => 62, 'post_id'=> 109));
foreach($PostLike as $subarray) {
     foreach($subarray as $name => $value) {
              if ($name == 'user_id') {
                echo $value . "\n";
         }

     }

}

输出:

47
62

演示:https://eval.in/454992

如果你想搜索一个特定的值,你可以这样做:

$PostLike = array(array('user_id' => 47, 'post_id' => 109), array('user_id' => 62, 'post_id'=> 109));
$key = array_search(62, array_column($PostLike, 'user_id'));
if($key !== false){
      echo $PostLike[$key]['user_id'];
} else {
      echo 'not present';
}

输出:

62

【讨论】:

  • 感谢您的回复,如果是这种情况,那么我需要为 ids 创建数组,因为我想匹配 来自“ids”数组的 ID。有什么线索吗?
  • 在您当前的代码中,您是否尝试查找数组中是否存在特定 id(例如47)?
  • 好的,在我的例子中,它创建了 arrayArray([user_id] => 47 [post_id] => 107),但它为每个帖子提供了数组,我无法让它工作对于每篇文章,每篇文章都是不同的,(我在我的网站上实施的一种“喜欢不一样”的系统)
  • 您的数组结构不像我发布的那样?
  • 是的,嗨,我试过了,没有结果我得到“调用未定义函数 array_column()”
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2018-05-05
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多