0

Not sure if I've worded that correctly however, the below could illustrate what I'm trying to achieve better..

I have a multidimensional array where I would like to capture a specific element from the last index within an array foreach

Array:

    [Something] => Array
(
    [Something1] => Array
    (
        [0] => Array
        (
            [@attributes] => Array
                (
                    [DataID] => Data
                    [DataID] => Data
                    [DataID] => Data
                    [DataID] => Data
                )

            [Something1.1] => Array
            (
                [Something1.1.1] => Array
                (
                    [0] => Array
                    (
                        [DataID] => Data
                        [Date] => YYYY-MM-DD
                        [DataID] => Data
                        [DataID] => Data
                        [DataID] => Data
                        [DataID] => Data
                    )
                    [1] => Array
                    (
                        [DataID] => Data
                        [Date] => YYYY-MM-DD
                        [DataID] => Data
                        [DataID] => Data
                        [DataID] => Data
                        [DataID] => Data

                    )
                    [2] => Array (last returned)
                    (
                        [DataID] => Data
                        [DateLASTRETURNED] => YYYY-MM-DD
                        [DataID] => Data
                        [DataID] => Data
                        [DataID] => Data
                        [DataID] => Data

                    )
                )
            )
            [Something1.2] => Array
            (
                [Something.1.2.1] => Array
                    (
                        [0] => Array
                    (
                        [DataID] => Data
                        [Date] => YYYY-MM-DD
                        [DataID] => Data
                        [DataID] => Data
                        [DataID] => Data
                        [DataID] => Data
                    )
                    [1] => Array
                    (
                        [DataID] => Data
                        [Date] => YYYY-MM-DD
                        [DataID] => Data
                        [DataID] => Data
                        [DataID] => Data
                        [DataID] => Data

                    )
                    [2] => Array (last returned)
                    (
                        [DataID] => Data
                        [DateLASTRETURNED] => YYYY-MM-DD
                        [DataID] => Data
                        [DataID] => Data
                        [DataID] => Data
                        [DataID] => Data
                    )
                )
            )
        )
    )
)

As you can see in brackets (last returned), I need the value within a specified element from the last returned in foreach "Something1.*) - Specifically, This field holds Date YYYY-MM-DD and would like to store into $ to reuse elsewhere.

Hopefully that makes sense, look forward to some help!

5
  • 1
    Is the depth of the targeted elements always the same? or might you have deeper keys like: Something.1.2.1.1.1? Have you tried to write any code for this yourself? This would help give volunteers more context. Is this coming from a parsed XML document? There may be a better/earlier way to handle this task. Commented Nov 16, 2021 at 0:16
  • 1
    Please always present your input data as var_export() not print_r() so that volunteers can instantly use it. It is impossible to have duplicate keys in a given level of an array. DataID occurs over and over within subarrays. Commented Nov 16, 2021 at 1:28
  • Hi Mick - thanks for replying! No deeper keys however 0,1,2,3 (results of data) may be longer in some cases and its crucial I can capture the “Date” in the last index within Something1.1,1.2,1.3 etc into a variable so it can be used in other areas of the code. I’ve tried however I cannot target the last index within a foreach loop - any ideas? Commented Nov 16, 2021 at 1:47
  • 2
    Please edit your code to provide a valid input data as var_export() output AND show use the EXACT desired output that you desire from that input. Make sure that your input is sufficiently expressive of the variability of your project data. Commented Nov 16, 2021 at 1:49
  • The structure you show is impossible - you have multiple keys with the same name; please read up on how and why to create a minimal reproducible example. Also, the presence of "@attributes" makes me suspect you've converted a SimpleXML object to an array; that's generally a bad idea, as SimpleXML has facilities for doing things more easily than with plain arrays; see the examples in the manual. Commented Dec 4, 2021 at 21:21

2 Answers 2

0

You can do something like this. First accessing until the desired level, then pick the last array of each, check if it is an array and then print the value "Date".

Assuming that the multi-array in the example is stored in a variable named $array:

foreach($array["something"]["Something1"] as $value) {
    foreach($value as $value1){
        if(is_array(end($value1))) {
            echo(end($value1)["Date"]);
        }
    }
}

In case your multi-array deviates from the example you have indicated maybe you should add some extra validation.


Edited to show an example saving the values into a variable instead of printing them.

// First declare an array to store all values
$var = array();

// Then extract all values and save them into $var
foreach($array["something"]["Something1"] as $value) {
    foreach($value as $value1){
        if(is_array(end($value1))) {
            array_push($var, end($value1)["Date"]); // Add the value at the end of the $var array
        }
    }
}

// Finally you have all values stored into the $var array

// If you know the number of values, you can access them one by one
$var[num]; // Where 'num' is the position of the value stored into the array (0,1,2...)

// Or you can loop it

foreach ($var as $date) {
    // do whatever with each $date value
}
Sign up to request clarification or add additional context in comments.

3 Comments

I would like to store the solution into a variable so it can be used in other areas of the code, what would be the solution for this instead if printing it?
@AG9 You are getting a String, the problem is that you are getting more than one value because your multiarray has different "Date" values, so then you'll need to store it into an array. First declare the array outside the foreach: $var = array(); Then instead of printing save the value into the array: array_push($var, end($value1)["Date"]); Finally you'll be able to access each value manually: $var[num] where num is the position of the value into the array or you'll be able to loop it. I'll update the answer.
Do you think you can help with this also? stackoverflow.com/questions/69992013/…
0

If you want to get the latest element from each element inside "Something1.*". You can try something like this:

$array = [
    'Something' => [
        'Something1' => [
            [
                "@attributes" => array(
                    'DataID_1' => "Data",
                    "DataID_2" => "Data",
                    "DataID_3" => "Data",
                ),
                "Something1.1" => array(
                    "Something1.1.1" => array(
                        array(
                            "DataID_1" => "data",
                            "Date" => "YYYY-MM-DD",
                            "DataID_2" => "data",
                            "DataID_3" => "data",
                        ),
                        array(
                            "DataID_1" => "data",
                            "Date" => "YYYY-MM-DD",
                            "DataID_2" => "data",
                            "DataID_3" => "data",
                        ),
                        array(
                            "DataID_1" => "data",
                            "Date" => "YYYY-MM-DD last",
                            "DataID_2" => "data",
                            "DataID_3" => "data",
                        ),
                    ),
                ),
                "Something1.2" => array(
                    "Something1.2.1" => array(
                        array(
                            "DataID_1" => "data",
                            "Date" => "YYYY-MM-DD",
                            "DataID_2" => "data",
                            "DataID_3" => "data",
                        ),
                        array(
                            "DataID_1" => "data",
                            "Date" => "YYYY-MM-DD",
                            "DataID_2" => "data",
                            "DataID_3" => "data",
                        ),
                        array(
                            "DataID_1" => "data",
                            "Date" => "YYYY-MM-DD last",
                            "DataID_2" => "data",
                            "DataID_3" => "data",
                        ),
                    ),
                ),
            ],
        ],
    ],
];

$dates = [];
$something1 = $array['Something']['Something1'];

foreach ($something1 as $something_1) {                 // loop through 'Something1'
    foreach ($something_1 as $key => $something_1_1) {  // loop through each element of 'Something1'.
        if (str_starts_with($key, 'Something1.')) {     // if key starts with 'Something1.' PHP >= 8.0
            foreach ($something_1_1 as $key => $something_1_1_1) {
                $last_element = end($something_1_1_1);  // get last element of array
                $dates[] = $last_element['Date'];       // OUTPUT: YYYY-MM-DD last
            }
        }
    }
}

var_dump($dates); // This array will contain your dates.

// You can also use the following code to loop through dates:
foreach ($dates as $date) {
    echo $date; // OUTPUT: YYYY-MM-DD last
}

//OR access the dates in the following way:
$first_date = $dates[0];                    // get first date. and so on..
$last_date = $dates[count($dates) - 1];     // get last date.

Please note these functions:
str_starts_with() is availabel since PHP8.0.
end() Set the internal pointer of an array to its last element.

2 Comments

I would like to store the solution into a variable so it can be used in other areas of the code, what would be the solution for this instead if printing it?
Check the updated answer. I think it should fulfill your needs.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.