简体   繁体   中英

How to access elements of array in php

Below is the code snippet:

$resultArray = explode("\n",$cmd);
print_r($resultArray);
$tempArray = array();
foreach($resultArray as $key){
        $tempArray = explode(" ",$key);
         print_r($tempArray);
}

first print gives output:-

Array
(

 [0] => AA-BB-E3-1B-81-6A 10.10.10.2
 [1] => CC-DD-E3-1B-7E-5A 10.10.10.3
)

Second print gives output:-

Array
(
    [0] => AA-BB-E3-1B-81-6A
    [1] => 10.10.10.2
)
Array
(
    [0] => CC-DD-E3-1B-7E-5A
    [1] => 10.10.10.3
)
Array
(
    [0] => 
)

Assuming there will be many entries of mac addresses corresponding mac addresses, I want to store them in separate variables for further use.

Please help. I am new to PHP, learning on my own. Any help is appreciated.

eidt 1: Expected output should be two arrays, one each for mac address and Ip Address from which I would be able to loop through and query database for each mac address.

Well I'm not sure what you want to do, but from the little I understood is to separate the mac addresses:

$resultArray = explode("\n", $cmd);
print_r($resultArray);
$tempArray = array();
foreach($resultArray as $key){
    $dm = explode(" ", $key);
    $tempArray[] = $dm[0];
}
print_r($tempArray);

The result would be:

Array
(
    [0] => AA-BB-E3-1B-81-6A
    [1] => CC-DD-E3-1B-7E-5A
     .
     .
     .
)

It would be much better if you put the expected result, in order to help you better.

You forget [] for tempArray:

$resultArray = explode("\n",$cmd);
print_r($resultArray);
$tempArray = array();
foreach($resultArray as $key){
        $tempArray[] = explode(" ",$key);
         print_r($tempArray);
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM