如何创建从mysql数据库中选择的新数组

时间:2014-01-16 00:03:47

标签: php mysql arrays sorting

我正在尝试使用PHP将数据从一个表移动到另一个表在mysql数据库中。原始表具有一对多关系的数据。有一列包含project_id(value_object_id - 这是多列),另一列(value_field_id)包含一个键,用于定义最后一列(value_charvalue)中存储的数据类型。我已经成功地使用以下代码提取所有数据,但是我无法弄清楚如何循环遍历每条记录以确定它是否是一个新的project_id,在value_field_id列中包含14,19或20,以及如何将新记录的数据放入数组中。每条新记录都需要包含原始表中3条记录的信息。感谢您提供的任何帮助或指示。

<?php
$link = mysqli_connect("localhost", "username", "password", "test");

/* check connection */
if (mysqli_connect_errno()) {
    printf("Connect failed: %s\n", mysqli_connect_error());
    exit();
}

$query = "SELECT value_object_id, value_field_id, value_charvalue FROM custom_fields_values ORDER BY value_object_id";

$result = mysqli_query($link, $query);

//  Add array for newly selected data????
//  $new_array = array();

/* numeric array */
while($row = mysqli_fetch_array($result, MYSQLI_NUM)) { 
    // Add test to determine if value_field_id is = 14, 19 or 20
    // $new_array[project_id] = value_object_id
    // If value_field_id = 19, $new_array[name] = value_charvalue
    // If value_field_id = 14, $new_array[email] = value_charvalue
    // If value_field_id = 20, $new_array[phone] = value_charvalue

    $project_id = $row[0];
    $next_row = $row[1];    
    $third_row = $row[2];
    printf('%s, %s, %s \n', $project_id, $next_row, $third_row);
    } 

/* free result set */
mysqli_free_result($result);

/* close connection */
mysqli_close($link);

?>

3 个答案:

答案 0 :(得分:0)

<?php

$projects = [];

while(...) {
  ...

  $fieldname = ...;
  $fieldvalue = ...;

  if (!isset($projects[$project_id]))
    $projects[$project_id] = [];
  $projects[$project_id][$fieldname] = $fieldvalue;
}

print_r($projects);

如果您使用的是古老版本的PHP,请将[]替换为array()

答案 1 :(得分:0)

首先,您需要确定value_field_id是19,14还是20。

// The field id's that you are interested in
$value_field_ids = array(19, 14, 20);

$project_id = array();

// I'm not sure why you would prefer numeric ids instead of associative?
while($row = mysqli_fetch_array($result, MYSQLI_NUM)) {

    // Here we check if the value_field_id is 19, 14 or 20
    if(in_array($row[1], $value_field_ids)) {
        $project_id[] = array($row);
    }

    $project_id = $row[0];
    $next_row = $row[1];  
    $third_row = $row[2];   
    printf('%s, %s, %s \n', $project_id, $next_row, $third_row);
}   

// At this point you have the entire data stored in $result, as an array
// Try var_dump($result);

你有它 - 你新创建的数组。

答案 2 :(得分:0)

使用WHERE value_field_id IN (14, 19, 20)

$query = "SELECT value_object_id, value_field_id, value_charvalue FROM custom_fields_values ORDER BY value_object_id";

变为

$query = "SELECT value_object_id, value_field_id, value_charvalue FROM custom_fields_values WHERE value_field_id IN (14, 19, 20) ORDER BY value_object_id";

并操纵您想要的任何内容或直接插入其他表格。