dpwqicw157673 2015-03-24 00:07
浏览 14

以编程方式构造数组

I'm writing a PHP web app that uses XML documents from an API. I have to construct many products from the returned XML data.

What I'm doing right now is using xpath and a loop to pull all of the objects into an array of sub-arrays. Then I loop through the array of arrays and pull specific arrays into their own named array. Is there a way to do this with a function or class constructor?

My current code looks something like this:

if ( $products_results_list[$key]["sChgDesc"] == "Small Box" ) {
    $small_box = array(
        "ChargeDescID" => $products_results_list[$key]["ChargeDescID"],
        "sChgDesc" => $products_results_list[$key]["sChgDesc"],
        "dcPrice" => $products_results_list[$key]["dcPrice"],
        "dcTax1Rate" => ".0" . $products_results_list[$key]["dcTax1Rate"],
        "dcInStock" => $products_results_list[$key]["dcInStock"],
    );
}

After writing the above if statement about 8 times, with many more times needed, I'm thinking there must be a better practice than just writing everything out.

I want to do something like:

product_constructor($argument, $product_name) {
  if ( $arguement ) {
    $product_name = array(
        "ChargeDescID" => $products_results_list[$key]["ChargeDescID"],
        "sChgDesc" => $products_results_list[$key]["sChgDesc"],
        "dcPrice" => $products_results_list[$key]["dcPrice"],
        "dcTax1Rate" => ".0" . $products_results_list[$key]["dcTax1Rate"],
        "dcInStock" => $products_results_list[$key]["dcInStock"],
    );
}

and then just call the function or constructor as needed like:

product_constructor( '$products_results_list[$key]["sChgDesc"] == "Small Box"', '$small_box');

I actually tried the above code, but it was throwing errors. Despite working with PHP daily, I still don't know much about constructors, and figured this might be the perfect opportunity to learn how to do this correctly.

I'm not sure if classes are the right choice for this since I'm going to need to pull the products themselves into product package classes later.

  • 写回答

0条回答 默认 最新

    报告相同问题?

    悬赏问题

    • ¥15 数学建模招标中位数问题
    • ¥15 phython路径名过长报错 不知道什么问题
    • ¥15 深度学习中模型转换该怎么实现
    • ¥15 HLs设计手写数字识别程序编译通不过
    • ¥15 Stata外部命令安装问题求帮助!
    • ¥15 从键盘随机输入A-H中的一串字符串,用七段数码管方法进行绘制。提交代码及运行截图。
    • ¥15 TYPCE母转母,插入认方向
    • ¥15 如何用python向钉钉机器人发送可以放大的图片?
    • ¥15 matlab(相关搜索:紧聚焦)
    • ¥15 基于51单片机的厨房煤气泄露检测报警系统设计