如何在多维数组中执行array_search?

时间:2016-02-12 09:37:20

标签: php arrays

我有这段代码:

$order_list = array ( array ("tangible", 1, 8, 33, 19000),
                      array ("tangible", 1, 9, 8, 19000),
                      array ("tangible", 6, 3, 24, 19000),
                      array ("tangible", 6, 2, 10, NULL),
                      array ("tangible", 1, 17, 11, 28000));

$key = array_search(3, array_column($order_list, $order_list[2]));

我希望根据$order_list[$i][3]得到$order_list[$i][2]的值。

例如,如果我把:

3我会得到24作为回报

9我会得到8作为回报

依旧......

我尝试使用array_search:

$key = array_search(3, array_column($order_list, $order_list[2]));

但是我收到了这个错误:

Warning: array_column(): The column key should be either a string or an integer in /home/***/public_html/***.php on line 8

Warning: array_search() expects parameter 2 to be array, boolean given in /home/***/public_html/***.php on line 8

在这种情况下如何执行array_serach?谢谢。

3 个答案:

答案 0 :(得分:1)

<?php

$search = 9;

$order_list = array ( array ("tangible", 1, 8, 33, 19000),
                  array ("tangible", 1, 9, 8, 19000),
                  array ("tangible", 6, 3, 24, 19000),
                  array ("tangible", 6, 2, 10, NULL),
                  array ("tangible", 1, 17, 11, 28000));




foreach ($order_list as $string){

    if (in_array($search,$string)){
       //repsonse here
    }
}
?>

答案 1 :(得分:1)

我创建了一个通用函数来获取2&lt; d d数组中当前值的下一个值。看看下面的功能。另请查看函数的变量描述以了解函数中的输入:

/***
 * @param array $array input array
 * @param $search_value value that need to be searched
 * @param $search_index index of inner array where current value exists
 * @return next value of current value
 */
function getNextSequence(array $array, $search_value, $search_index)
{
    $result = null;
    $key = array_search($search_value, array_column($array, $search_index));
    if ($key !== false) {
        $result = (isset($array[$key][$search_index + 1])) ? $array[$key][$search_index + 1] : null;
    }

    return $result;
}

$order_list = array(
    array("tangible", 1, 8, 33, 19000),
    array("tangible", 1, 9, 8, 19000),
    array("tangible", 6, 3, 24, 19000),
    array("tangible", 6, 2, 10, NULL),
    array("tangible", 1, 17, 11, 28000)
);

var_dump(getNextSequence($order_list, 3, 2)); //output: int(24)
var_dump(getNextSequence($order_list, 9, 2)); //output: int(8)
var_dump(getNextSequence($order_list, 10, 2)); //output: Null
var_dump(getNextSequence($order_list, 2, 2)); //output: int(10)

答案 2 :(得分:1)

另一种方式......

$this->load->helper('download');
$data = "Here is some text! \n";
$data .= 'Here is some text!';
$name = 'mytext.txt';
force_download($name, $data,TRUE);