1

I have created 2 array, I'm trying to show my first array to another array. So I used foreach statement so I can show each value in my 2nd array like this

$first = array(
    '12:00 AM',
    '1:00 AM',
    '2:00 AM',
    '3:00 AM',
    '4:00 AM',
    '5:00 AM',
    '6:00 AM',
    '7:00 AM',
    '8:00 AM',
    '9:00 AM',
    '10:00 AM',
    '11:00 AM'
);

$2nd = array('body' =>array(),);

foreach ($first as $value) {
    $2nd['body'] = $value;
}

echo json_encode($2nd); ?>

The problem is only the 11:AM is showing.

2
  • 2
    you can not use $2nd you cant start your variable name using number Commented Oct 2, 2015 at 10:50
  • You are tracing through the complete $first array but you are not preserving them. So the most recent value is being stored to your second array.For that you have to push the values to the second array. Again the variable name can't start with number Commented Oct 2, 2015 at 10:57

4 Answers 4

2

First: you can't start a variable name with a number (PHP Docs), and second you need to append ( added [] ) the value to the array, otherwise you will only get the last value.

$first = array( '12:00 AM', '1:00 AM', '2:00 AM', '3:00 AM', '4:00 AM', '5:00 AM', '6:00 AM', '7:00 AM', '8:00 AM', '9:00 AM', '10:00 AM', '11:00 AM' );

$second= array( 'body' => array(), );

foreach ( $first as $value ) {
    $second['body'][] = $value;
}

echo json_encode($second);

You could also use a shorter way:

$first = array( '12:00 AM', '1:00 AM', '2:00 AM', '3:00 AM', '4:00 AM', '5:00 AM', '6:00 AM', '7:00 AM', '8:00 AM', '9:00 AM', '10:00 AM', '11:00 AM' );

$second = array( 'body' =>  $first );

echo json_encode( $second );
Sign up to request clarification or add additional context in comments.

Comments

1

You can use the = php equal operator

$first = array( '12:00 AM', '1:00 AM', '2:00 AM', '3:00 AM', '4:00 AM', '5:00 AM', '6:00 AM', '7:00 AM', '8:00 AM', '9:00 AM', '10:00 AM', '11:00 AM' );

$second['body'] = $first;

print json_encode($second);

Tip: variable names cannot start with a digit, so rename the $2nd to $second http://php.net/manual/en/language.variables.basics.php

Here working sample https://eval.in/443545

Comments

0

Change variable name. (i.e) cannot begin with digit. Consider using it as $second

$first = array( '12:00 AM', '1:00 AM', '2:00 AM', '3:00 AM', '4:00 AM', '5:00 AM', '6:00 AM', '7:00 AM', '8:00 AM', '9:00 AM', '10:00 AM', '11:00 AM' );   

$second= array( 'body' => array(), );
foreach ( $first as $value ) 
    {
     $second['body'][] = $value;
    }
 echo json_encode($second);

Comments

0

You don't append your values from $first to $second['body'] but overwrite them. Either use the array_push function or $second['body'][] = $value; Edit: And yes, of course, respect the variable naming rules as already said in the other answers.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.