In_Array() and Multidimensional Array

in_array() and multidimensional array

in_array() does not work on multidimensional arrays. You could write a recursive function to do that for you:

function in_array_r($needle, $haystack, $strict = false) {
foreach ($haystack as $item) {
if (($strict ? $item === $needle : $item == $needle) || (is_array($item) && in_array_r($needle, $item, $strict))) {
return true;
}
}

return false;
}

Usage:

$b = array(array("Mac", "NT"), array("Irix", "Linux"));
echo in_array_r("Irix", $b) ? 'found' : 'not found';

Using in_array for multidimensional arrays

$array = array(
"0" => array(
"receiver_telmob" => "0707105396",
"0" => "0707105396"
),
"1" => array(
"receiver_telmob" => "0704671668",
"0" => "0704671668"
),
"2" => array(
"receiver_telmob" => "0707333311",
"0" => "0707333311"
)
);

$searchnumber = "0707333311";

foreach($array as $v) {
if ($v['receiver_telmob'] == $searchnumber) {
$found = true;
}
}

echo (isset($found) ? 'search success' : 'search failed');

search with in_array in multidimensional array

Try array_key_exists(): link

if(array_key_exists('name', $false['name'])) {
echo $false['name'][0]; // or [1] .. or whatever you want to echo
}

in_array() on multidimensional array

Using in_array search for values, but in your code Peter is a key. Then you can use array_key_exists instead:

$people = array(
"Peter" => array (
"test" => 0
),
"Joe"
);

if (array_key_exists("Peter", $people))
{
echo "Match found";
}
else
{
echo "Match not found";
}

Output

Match found

you can combine both since the name you're searching is sometimes the value like "Joe" in your example.

if (array_key_exists("Peter", $people) || in_array("Peter", $people)) {
echo "Match found";
} else {
echo "Match not found";
}

in_array() not working with two dimensional associative array?

You should use array_column() which will return the values from a single column in the input array as an array.

$product_auto_ids = array_column($array['cart_item'], 'product_auto_id');

In this case, it would return the following:

Array
(
[0] => 556729685
[1] => 951790801
)

Then you can use in_array() like you currently are.

in_array(556729685, $product_auto_ids);

How to reshape a flattened array to a multidimensional array in arbitray shape in Javascript?

Here's my solution:


const A = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12];
const C = [3, 4];

function unflattenArray(arr, dim) {
let elemIndex = 0;

if (!dim || !arr) return [];

function _nest(dimIndex) {
let result = [];

if (dimIndex === dim.length - 1) {
result = result.concat(arr.slice(elemIndex, elemIndex + dim[dimIndex]));
elemIndex += dim[dimIndex];
} else {
for (let i = 0; i < dim[dimIndex]; i++) {
result.push(_nest(dimIndex + 1));
}
}

return result;
}
return _nest(0);
}

console.log(unflattenArray(A, C));


Related Topics



Leave a reply



Submit