2

I want to display multiple arrays into one such that each time the object is created it get a key value and then forms a object to be more specific following is a short example.

How it is now:

name:[{},{},{},{}]
surname:[{},{},{},{}]
phone: [{},{},{},{}]

How I want it to be:

xyz:[{name:{}, surname{}, phone{}},
     {name:{}, surname{}, phone{}},
     {name:{}, surname{}, phone{}}]

I am exporting this in php so that I can use this JSON object in AngularJs ng-repeat directive.

following is the code:

  1. declaring array:

    $name = array();
    $surname= array();
    $phone= array();
    
  2. assigning values WHICH IS UNDER FOR EACH LOOP

    $name[] = $values ($values wil have the values for the loop)
    .....
    
  3. testing output

    <?php echo json_encode($name);
        echo json_encode($surname);
        echo json_encode($phone);
    ?>
    
5
  • Just put the array inside of that array:$finalArr = [ $name,$surname ]; Commented Jun 8, 2017 at 16:11
  • One small advice.I'd rather spend more time making a RESTful API which will handle all the background jobs.And form angular make the calls.Try out Slim it's easy and it will help you out a lot. Commented Jun 8, 2017 at 16:13
  • @FirstOne this is a magento site so data is coming via php in For loop Commented Jun 8, 2017 at 16:14
  • @Arslan.H Its a magento site working on MVC frame work only way to take the data is through this php variables in a for loop Commented Jun 8, 2017 at 16:15
  • @FirstOne yeah its looks correct let me try once Commented Jun 8, 2017 at 16:17

1 Answer 1

1

A simple way of doing it (run):

$name = array("name 1", "name 2");
$surname = array("surname 1", "surname 2");
$phone = array("phone 1", "phone 2");

$output = array();
for($i = 0; $i < count($name); $i++){
    $output[] = array(
            'name' => $name[$i],
            'surname' => $surname[$i],
            'phone' => $phone[$i],
        );
}

print_r($output);

Output:

Array
(
    [0] => Array
        (
            [name] => name 1
            [surname] => surname 1
            [phone] => phone 1
        )

    [1] => Array
        (
            [name] => name 2
            [surname] => surname 2
            [phone] => phone 2
        )

)

Note: It assumes all arrays are of same size and have same keys.

But maybe it would be better to instead of saving each value to 3 different variables and then running this script, try saving the values already into the array as the desired output (if possible, of course, since we can't know).

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.