PHP - get multiple columns from array

后端 未结 7 1850
星月不相逢
星月不相逢 2021-01-12 09:55

I have this array:

0 => array:3 [
    \"product_id\" => \"1138\"
    \"product_image\" => \"/resources/medias/shop/products/shop-6500720--1.png\"
           


        
7条回答
  •  时光说笑
    2021-01-12 10:32

    If I understand your question correctly, you could try a traditional foreach - it might be a little faster.

    function colsFromArray($array, $filterKeys) {
        $newArr = [];
        foreach($array as $key => $val) {
           $element = [];
           foreach($filterKeys as $filterKey) {
              $element[$filterKey] = $val[$filterKey];
           }
           $newArr[] = $element;
        }
    }
    

    (Not tested)

    The problem is that it seems too laggy, since it iterates twice over this

    Your original code isn't iterating twice over the same array. You won't be able to get around iterating over the main array and then the filterKeys array if you want to have an array where each element is another array of elements with keys from the filterKeys array.

提交回复
热议问题