循环遍历多维数组并查找匹配值
I'm looking for a way to loop through a multidimensional array and with an if (or simular) find matching values if key master is true.
The array:
Array
(
[0] => Array
(
[namn] => Vardagsrum
[IP] => 192.168.1.232
[rincon] => RINCON_000E58A64F1601400
[rincon_live] => RINCON_000E58A64F1601400
[master] => 1
)
[1] => Array
(
[namn] => Badrum
[IP] => 192.168.1.137
[rincon] => RINCON_B8E937580A5801400
[rincon_live] => RINCON_000E58A64F1601400
[slave] => 1
)
[2] => Array
(
[namn] => Kök
[IP] => 192.168.1.134
[rincon] => RINCON_000E58F8C9E001400
[rincon_live] => RINCON_000E58A64F1601400
[slave] => 1
)
)
If i got a master => true (in this case vardagsrum) I would like the loop to match all slave => true rincon_live values against the masters rincon value.
I dont know if that makes any sense at all but if I got one or more masters, I want to check the slaves rincon against the masters to see which slaves is connected to which master and after that do something.
Thanks for the help!
You'll probably want to use 2 loops. One to build the structure and another to do something with it. Quick mockup(haven't written PHP in a while):
<?php
$result = array();
foreach ($array as $item) {
if (!isset($result[$item['rincon']])) {
$result[$item['rincon']] = array(
'master' => null,
'slaves' => array(),
);
}
if (isset($item['master']) && $item['master']) {
// master
$result[$item['rincon']]['master'] = $item;
} else {
// probably slave, might want to rewrite the else to an elseif
$result[$item['rincon']]['slaves'][] = $item;
}
}
?>
Now $result
will contain an array with the rincon as a key and master/slaves in them like this:
<?php
$result = array(
'RINCON_000E58A64F1601400' => array(
'master' => array(
'namn' => 'foo',
'IP' => '127.0.0.1',
...
),
'slaves' => array(
array(
'namn' => 'foo',
'IP' => '127.0.0.1',
...
),
array(
'namn' => 'bar',
'IP' => '127.0.0.1',
...
),
)
)
)
and I assume you know how to loop through that