3

I have the following array structure:

[prod_prop] => Array
        (
            [45375] => Array
                (
                    [0] => 129|3|Mid-length
                )

            [45374] => Array
                (
                    [0] => 130|3|Long
                    [1] => 129|3|Mid-length
                )

            [45373] => Array
                (
                    [0] => 131|3|
                    [1] => 130|3|Long
                    [2] => 129|3|Mid-length
                )

        )

I want to loop through each parent number and output comma separated string of first part of second level array

So, how can I get a sting separated value for each number so desired result is as follows:

45375 -> returns 129

45374 -> returns 130,129

45373 -> returns 131,130,129

This is my current code which returns everything in the comma separated array not what im after:

 foreach($_POST['prod_prop'] AS $prop_ids) {
            $list = implode(",",$prop_ids);    
            echo $list;
        }

Returns: 131|3|131|3|,130|3|Long131|3|,130|3|Long,129|3|Mid-length 131|3|,130|3|Long,129|3|Mid-length

5
  • 2
    Then go for it! Try it, maybe you will surprise yourself :D Commented Mar 11, 2015 at 12:53
  • I've tried but not sure how identify the values in the 2nd level of the array? I can loop though fine for each top level Commented Mar 11, 2015 at 12:54
  • 1
    Then show us your attempt! Commented Mar 11, 2015 at 12:56
  • Hmmm i think i see the error of my ways! Each element is a string already with | seperater this should be another array instead Commented Mar 11, 2015 at 13:10
  • It would make the coding for sure easier Commented Mar 11, 2015 at 13:11

5 Answers 5

2
foreach ($_POST['prod_prop'] as $prop_ids) {
    $list = join(',', array_map(
        function ($id) { return current(explode('|', $id)); },
        $prop_ids
    ));    
    echo $list;
}
Sign up to request clarification or add additional context in comments.

5 Comments

This works well , however i should probably due a sub array rather than explode on the string containing |. thanks
How does this exactly work? does map to elements that contain |
An array_map is the same as $res = array(); foreach ($arr as $i) $res[] = func($i);, where func is the function given above. Play around with it.
last question i'm struggling to get the parent KEYs 45375 ,45374, 45373 etc. Trying key($_POST['prod_prop']) but it stays on the first key?
foreach ($_POST['prod_prop'] as $key => $prop_ids)
0

You can archive this with using these functions:- end(),explode(),trim(). Use the code below

$last = end($_POST['prod_prop']);
 foreach($_POST['prod_prop'] AS $prop_ids) {
foreach($prop_ids as $s){
$list .= ",".explode("|",$s)[0];
}
if($prop_ids==$last){
echo trim($list,",")."";
}
else{
echo trim($list,",").",";
}


        }

Try it for yourself.Hope this helps you.

2 Comments

This isn't really my desired result this brings back: 131|3|131|3|,130|3|Long131|3|,130|3|Long,129|3|Mid-length 131|3|,130|3|Long,129|3|Mid-length
@darvey it was just a hint, if you want your desired result use implode with explode. Wait posting your answer
0

Why don't you scroll through array, implode() its values, and apply regex onto it?

$res = Array();
foreach($_POST["prod_prop"] as $bID=>$bLists) {

   $str = implode(",", $bLists); // get list of values comma separated

   preg_match_all("/(^|,)(\d+)/", $str, $m); //get all digits, which follow string start or comma

   if (Count($m[1])) { // if value found - store it in $res array
      $res[$bID] = implode(",", $m[1]);
   }
}

One note: I'm not sure about syntax of regex in PHP. In javascript the following works

var str = "131|3|,130|3|Long,129|3|Mid-length";
$('#result').html(str.match(/(^|,)(\d+)/g));
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<span id="result"></span>

Comments

0

This sounds like a good use-case for array_reduce. Try this:

foreach($_POST['prod_prop'] as $id => $properties) {

    $result = array_reduce($properties, function($val, $item) {

        return $val . ',' . substr($item, 0, strpos($item, '|'));
    });

    echo $result;
}

Comments

0

Use iterated calls of strtok() calls on each subarray to isolate the substring before the first pipe, then implode() the truncated elements before echoing.

foreach ($_POST['prod_prop'] as $prop_ids) {
    echo implode(',', array_map(fn($v) => strtok($v, '|'), $prop_ids)) . '<br>';
}

Comments

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.