0

I'm using CakePHP to create a products database system. In CakePHP, I have an array of all products in the 'products' table. Each product (an element in the 'products' array) has a function 'toArray()'. This converts the product into an associative array. How could I take an array of all the products and add the 'toArray()' of each product to a new array. This is my current flow:

$products = [$product1, $product2, $product3];
$newArr = [];
foreach($products as $product) {
    $newArr[] = $product->toArray();
}

Is there a one-liner for something like this?

1
  • thanks @quickshiftin, that went right over my head. Commented Feb 3, 2015 at 16:40

1 Answer 1

1

I don't think you could quite oneline this (without functionalizing it, anyway), but you don't need to duplicate data unless you need to keep the original format as well as the reformatted version.

foreach($products as $key => $product){
    $products[$key] = $product->toArray();
}

Will change your exisiting array to the reformatted version.

Sign up to request clarification or add additional context in comments.

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.