简体   繁体   中英

PHP - How to generate unconventional data from a multidimensional array

after 10 years I'm starting programming again, just for fun. I'm struggling with the following code in PHP:

This is what I get from the database:

$data[0] = ['id' => NULL, 'titel' => NULL, 'category_id' => NULL];

$data[1] = ['id' => '1', 'titel' => 'Apple', 'category_id' => '123'];
$data[2] = ['id' => '2', 'titel' => 'Pear', 'category_id' => '123'];
$data[3] = ['id' => '3', 'titel' => 'Orange', 'category_id' => '123'];

$data[6] = ['id' => '6', 'titel' => 'Strawberry', 'category_id' => '297'];
$data[7] = ['id' => '7', 'titel' => 'Blueberry', 'category_id' => '297'];
$data[8] = ['id' => '8', 'titel' => 'Raspberry', 'category_id' => '297'];

$data[12] = ['id' => '12', 'titel' => 'Cucumber', 'category_id' => '557'];
$data[13] = ['id' => '13', 'titel' => 'Pumpkin', 'category_id' => '557'];

That's the string I have to generate for the javascript:


'choices': {

    0: {
        text: [''],
        value: ['']
    },
    123: {
        text: ['Apple', 'Pear', 'Orange'],
        value: ['1', '2', '3']
    },
    297: {
        text: ['Strawberry', 'Blueberry', 'Raspberry'],
        value: ['6', '7', '8']
    },
    557: {
        text: ['Cucumber', 'Pumpkin'],
        value: ['12', '13']
    }

}

Can someone help me on that one? I'm trying something like this, but struggling with:

  $text = 'text: [';
  $value = 'value: [';
  $final_str = '';
  $current_category_id = '';

  foreach ($data as $foo) {
    if (($foo['category_id'] != $current_category_id)) {
      $text .= ']';
      $value .= ']';
      $final_str .= '}, ' . $product_id . ': { ' . $text . $value;
      $text = 'text: [';
      $value = 'value: [';
    }

    $text .= '\'' . $foo['titel'] . '\', ';
    $value .= '\'' . $foo['id'] . '\', ';
    $current_category_id = $foo['category_id'];
  }
  $text .= ']';
  $value .= ']';
  $final_str .= $current_category_id . ' { ' . $text . $value;

Thank you very much!

Instead of manually building a string, you should generate the data structure and then output it via json_encode:

<?php

$return = [];
foreach($data as $d) {
    $cat_id = intval($d['category_id']);
    
    if (!isset($return[$cat_id])) {
        $return[$cat_id] = [
            'text' => [],
            'value' => [],
        ];
    }
    
    $return[$cat_id]['text'][] = strval($d['titel']);
    $return[$cat_id]['value'][] = strval($d['id']);
}

?>

<script>
    ...
    'choices': <?= json_encode($return); ?>
    ...
</script>

If you do echo json_encode($return); it will output:

{"0":{"text":[""],"value":[""]},"123":{"text":["Apple","Pear","Orange"],"value":["1","2","3"]},"297":{"text":["Strawberry","Blueberry","Raspberry"],"value":["6","7","8"]},"557":{"text":["Cucumber","Pumpkin"],"value":["12","13"]}}

You can see it in action at https://3v4l.org/VrHXO

First things first: don't try to build that string by hand, you'll just get headaches. Instead, build up the array structure in PHP, and then use json_encode to convert it to JSON.

You can then either cheat and use the JSON directly as a JavaScript variable (always remember that JSON and JavaScript are not the same language, but JSON is almost always valid JavaScript), or use JSON.parse to parse it properly.

The next trick is that since you're building an associative array, you don't need to track the "current" category, you can just add each item into the right place:

$data_by_category = [];
foreach ( $data as $item ) {
    // Force the vategory to be an integer, 0 for null
    $category_id = (int)$item['category_id'];
    
    // Set up the category the first time you see it
    $data_by_category[$category_id] ??= ['text'=>[], 'value'=>[]];
    
    // Add the items as you see them, forcing them to be strings
    $data_by_category[$category_id]['text'][] = (string)$item['titel'];
    $data_by_category[$category_id]['value'][] = (string)$item['id'];
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM