0

I have some difficulties with PHP Arrays. I'm trying to foreach some values, order them with array_multisort and foreach them again so I can create some kind of code. So what I'm doing is, I'm passing json object as:

"options": [
                    {"key": "Ships From", "value": "Russia"},
                    {"key": "Color", "value": "Green"},
                    {"key": "Size", "value": "M"},
                    {"key": "Material", "value": "Flex"}
                   
            ],

So this is received from frontend, and I'm foreaching them like so:

public function findAttribute($product_id, $values)
    {
            $array = array();
            
            foreach ($values as $key => $value) {
                $getAttr = $this->attribute($value['key']);
    
                $getAttrValue = $this->attributeValue($getAttr->id, $value['value']);
    
                $code = $getAttr['label'] . '=' . $getAttrValue['value'];
                $collection = array_push($array, array($getAttr->default_order, $code));
            }
    
            array_multisort($array, SORT_ASC);
}

As you can see I have $getAttr and $getAttrValue, that selects values from database, in order to get default_order (integer) so I can sort them with multisort. So actually this code works as expected, and when I write (after multisort) like:

foreach($array as $key => $value){
            echo $value[1] .'/';
        }

I have expected value, but when I call that function it gives me that it returns NULL, if I change echo to return, I have only first array. If I try like

foreach($array as $key => $value){
            $code = $value[1] .'/';
}
return $code;

No success as well. What should I do?

1
  • Have you look at PHP methods array_search ? Commented Feb 3, 2021 at 13:24

2 Answers 2

1

Because in each iteration you assign a new value to $code so you will only get the last $value [1] in the array (after arranged). If you want to return a string concatenating all values, you could do as this:

$code = '';
foreach($array as $key => $value){
    $code .= $value[1] .'/';
}
return $code;
Sign up to request clarification or add additional context in comments.

1 Comment

@somebodytolove You are welcome! If you find my answer to be correct and helpful, please mark it as correct and upvote it.
0
$code = array();
foreach($array as $key => $value){
        $code = $value[$key] .'/';
}
return $code;

Implement your code i hope that will work.

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.