2

This is my array

 Array (
    [camp] => 1523270715437137241
    [seg] => Array
        ([0] => Array
                ( [id] => 1524043028577447661
                    [ben] => 10000
                    [rule] => Array
                        ([0] => Array
                                ([id] => 1524050160515158364
                                    [logic] => #3 and # 4
                                )))))

I want to get the values belongs to 'rule' array which is inside three big arrays without using foreach loop. Is it possible?

Shiromi
  • 159
  • 1
  • 9
  • 2
    Much depend if you know all the upper level of the array. If so you can acces this array with $ruleArray= $array['camp']['seg'][0]['rule']. Otherwise foreach is the best solution – Lucarnosky Apr 19 '18 at 10:12
  • 1
    Please provide array in format of php code – Rohan Khude Apr 19 '18 at 10:15
  • `foreach( $array['seg'] as $key => $data) print_r($data['rule']);` – Dale Apr 19 '18 at 10:20
  • @Shiromi the duplicate link provided isn't an exact match, but I'm not willing to vote to reopen this question while you have no coding attempt. The dupe page uses functional looping and `array_column()`. Iterating is still iterating, I can't see the bias against a looping language contructs. I love a well-placed `array_column()` call, but it is usually a heavier weapon than a `foreach()`. The only other _hackish_ way that I can think of would be convert to json, then write some horrible regular expression to isolate the subarray and then decode it back to an array ... yuck. – mickmackusa Apr 22 '18 at 11:25
  • If you want your question to be reopened, you will need to improve your question. We want to see a ready-to-use variable containing your input data. We want to see your best coding attempt. We want to see your desired output. If you have error messages, we want to see them. – mickmackusa Apr 22 '18 at 11:32

1 Answers1

0

Try this function, recursive way:

function getval($arrs, $k) {
    foreach($arrs as $key=>$val) {
        if( $key === $k ) {
            return $val;
        }
        else {
            if(is_array($val)) {
                $ret = getval($val, $k);
                if($ret !== NULL) {
                    return $ret;
                }
            }
        }
    }
    return NULL;
}

print_r(getval( $array, "rule" )); // prints the array value of element with key "rule"

This can go through every element of the passed array, using foreach and recursion, until the key is found and returns its value.

Karlo Kokkak
  • 3,674
  • 4
  • 18
  • 33