Note that there are some explanatory texts on larger screens.

plurals
  1. POEchoing out an array and insert blank strings if the key doesn't exist in another array
    text
    copied!<p>I have an array of arrays like this:</p> <pre><code>[0] { Array[0] { First_Name =&gt; "john" } Array[1] { Last_Name =&gt; "smith" } Array[2] { Job =&gt; "Worker Ant" } } [1] { Array[0] { First_Name =&gt; "jane" } Array[1] { Last_Name =&gt; "smith" } } </code></pre> <p>etc. Let's call it <code>peopleArray</code>;</p> <p>I also have an array of keys such as <code>"First_Name, Last_Name"</code> that would match the keys in the above examples. I'll call it <code>headingArray</code>.</p> <p>I want to echo out <code>peopleArray</code> seperated by commas like this:</p> <p><code>"'john', 'smith', 'Worker Ant'"</code></p> <p><code>'jane','smith',''</code></p> <p>And have the values without keys in the <code>headingArray</code> be just an empty string.</p> <p>I've been trying something like this:</p> <pre><code>for($i=0; $i &lt; count($headingArray); $i++){ foreach($peopleArray as $row){ foreach($row as $data){ if(key($data) == $headingArray[$i]){ echo '"'.current($data).'",'; } } } //die(); echo "\r\n"; } </code></pre> <p>Where I loop through each header and try to match up the values, but it clearly doesn't work. </p> <p>There must be a simpler way of doing this. </p> <p>Can anyone help me out/point me in the right direction? I've been pounding my brain on this for hours.</p> <p>Edit: I've come up with this. It echoes all the values I need, but does some weird thing with skipping the ones that don't exist:</p> <pre><code>foreach($peopleArray as $person) { $prevKey = array(); $numItems = count($person); $i = 0; foreach($person as $heading) { foreach($person as $key =&gt; $value) { if(key($value) == $heading){ echo '"'.str_replace(',',' ',current($value)).'",'; $prevKey[] = key($value); break; } else if(in_array(key($value), $prevKey)) { } else { echo '"",'; } } //die(var_dump($prevKey)); $i++; } echo "\r\n"; } </code></pre> <p>I need it to return a blank string if it doesn't exist.</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload