简体   繁体   中英

rename key of newly added element in associative array

I have a array thats returned from a php query. result is like this.

okay, here is the for loop just after the select was done

  $row = $stmt->fetchAll(); $arraySize = sizeof($row); for($x = 0; $x < $arraySize;$x++) { // Gets rid of all the numeric KEY values $max = sizeof($row[$x])/2; for($i = 0; $i < $max;$i++) { unset($row[$x][$i]); } $row[$x][] = false; // appends a boolean value for the tick box in datatables $row['select'] = $row['9']; unset($row['9']); $json[] = $row[$x]; } echo json_encode($json); 
Array
    (
        [0] => Array
            (
                [uuid] => 365
                [name] => August_Kidsmeals.mp4
                [title] => 
                [path] => file://C:/wamp/www/chopperv2/video/library/
                [duration] => 00:30:00
                [uploaded_date] => 2014-07-22
                [uploaded_by] => admin
                [keyword] => 
                [comment] => 
            )

        [1] => Array
            (
                [uuid] => 368
                [name] => August_breakfast.mp4
                [title] => 
                [path] => file://C:/wamp/www/chopperv2/video/library/
                [duration] => 00:30:00
                [uploaded_date] => 2014-07-22
                [uploaded_by] => admin
                [keyword] => 
                [comment] => 
            )
    )

Now I want to push a extra element onto the array ( 'selected' ) before sending it via AJAX to a datatable.

I would like to custom name the KEY of the pushed element, but Im having difficulties doing this.

I have tried this. which works but its numeric.

$row[$x][] = true;

Its part of a For loop . This results in a 'appendation' of [9] => 1

I tried to rename the [9] with something like this

 $row['select'] = $row['9']; unset($row['9']); 

but to no avail. Please can someone slap me in the right direction.

This should be the result

  [0] => Array ( [uuid] => 365 [name] => August_Kidsmeals.mp4 [title] => [path] => file://C:/wamp/www/chopperv2/video/library/ [duration] => 00:30:00 [uploaded_date] => 2014-07-22 [uploaded_by] => admin [keyword] => [comment] => [select] => 1 // <<------ I WANT THIS ) 

A simple foreach should suffice and use & reference on each copy:

$rows = $stmt->fetchAll(PDO::FETCH_ASSOC); // no need to unsetting numeric indexed values, all are in associative now
foreach($rows as &$row) {
    $row['selected'] = true;
}

Just add the element to the desired row in your loop: (And maybe, if you olny want that selected row to the whole result)

if(9 == $x) {
 $row[$x]['select'] = 1;
 $result = $row[$x];
 break;
}

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