PHP - In an array like 1,3,6,7; how to select row 3? (lowest number below 6)
<p>I have an obscure array that follows product ID's and the respective details.</p>

<p>Here is an example of the array output :</p>

<pre><code>id - 1
stockCode - 113
Desc - Printer 1
Cost - R 113.00

id - 3
stockCode - 133
Desc - Printer 3
Cost - R 133.00

id - 6
stockCode - 163
Desc - Printer 6
Cost - R 163.00

id - 7
stockCode - 
Desc - Printer 6 Details
Cost - 

id - 8
stockCode - 
Desc - Printer 6 Extra
Cost - 
</code></pre>

<p>For a reason that is too long to explain, i would like to be able to loop through this array and within that loop and produce a certain outcome. </p>

<p>That being that any ID with data in only the second value and nothing in the first and third values, gets the second value appended to the preceding 2nd value of the key (ID) that came before the <strong>Here is where i get stuck</strong> current id. Once this has been done, the key must be deleted and the process continues.</p>

<p>Here is the code for that, the array is named $csvarray and $key would relate to the "id" in my example:</p>

<pre><code># Clean array - append 2nd values to previous values
foreach($csvarray as $key=&gt;$val)
{   
    // Imagine this is ID # 7 in the loop
    if ($val[0] == '' &amp;&amp; $val[1] !== '' &amp;&amp; $val[2] == '')
    {
        $writeTo = HOW TO I SELECT THE KEY BEFORE 7, IN THIS CASE 6
                   BUT IF IT WAS 6, THE KEY WOULD BE 3
        $csvarray[$writeTo][1] = $csvarray[$writeTo][1] . ', ' . $val[1];
        unset($csvarray[$key]);
    }
}
</code></pre>

<p>So in essence, i would like a find a way to select the key value preceding the current value while looping through an array...</p>

<p>If anyone would like to share some knowledge or has a suggestion or advice or any kind of input on this question, it would be great to hear!</p>

<p>Thank you!</p>

<p>EDIT : </p>

<p>Thanks for all your input! Given the input the correct approach would be something like this :</p>

<pre><code># Clean array - append 2nd values to preceeding key second value
$writeTo = null;
foreach($csvarray as $key=&gt;$val)
{   
    if ($val[0] == '' &amp;&amp; $val[1] !== '' &amp;&amp; $val[2] == '')
    {
        $csvarray[$writeTo][1] = $csvarray[$writeTo][1] . ', ' . $val[1];
        unset($csvarray[$key]);
    }
    else 
    {
        $writeTo = $key; 
    }
}
</code></pre>
