Viewed   88 times

How to create an array in PHP that with json_encode() becomes a thing with following structure:

Array(
[1] => Array(
    [id] => 1
    [data] => 45
)
[2] => Array(
    [id] => 3
    [data] => 54
)
);

 Answers

5

Try something like this:

//initialize array
$myArray = array();

//set up the nested associative arrays using literal array notation
$firstArray = array("id" => 1, "data" => 45);
$secondArray = array("id" => 3, "data" => 54);

//push items onto main array with bracket notation (this will result in numbered indexes)
$myArray[] = $firstArray;
$myArray[] = $secondArray;

//convert to json
$json = json_encode($myArray);
Friday, December 23, 2022
5

I played with your code to get it working :

function findKey($array, $keySearch)
{
    foreach ($array as $key => $item) {
        if ($key == $keySearch) {
            echo 'yes, it exists';
            return true;
        } elseif (is_array($item) && findKey($item, $keySearch)) {
            return true;
        }
    }
    return false;
}
Friday, December 16, 2022
1

Don't use strcmp :)

function custom_sort($a, $b) {
    return $a['revenue_certificate'] - $b['revenue_certificate'];
}

usort($data_array, 'custom_sort');

custom_sort should return a negative, 0, positive value when $a < $b, $a == $b, $a < $b respectively (just as strcmp does BTW).

Tuesday, September 20, 2022
 
groomsy
 
2

That is not valid JSON. The structure you are looking for would be something like:

[
 {"key1": ["package1", "package2", "package3"]},
 {"key2": ["package1", "package2", "package3", "package4"}]
          ^ An array as the value to the key "key1", "key2", etc..
]

At the PHP side, you would need something like:

  1. For every row fetched from MySQL
    • $arr[$key] = <new array>
    • for each package:
      • append package to $arr[$key]
  2. echo out json_encode($arr)
Friday, November 18, 2022
 
3

You can do it like this, do the calculation from the innermost of the array. Check the demo.

<?php
function f(&$array)
{
    foreach($array as $k => &$v)
    {
        if(is_array($v))
        {
            if(count($v) == count($v, 1))
            {
                unset($array[$k]);
                if($k == 'sum')
                {
                    $v =  array_sum($v);
                    $array[] = $v;

                }elseif($k == 'multiply'){
                    $v = array_product($v);
                    $array[] = $v;
                }else{

                    foreach($v as $vv)
                        $array[] = $vv;
                }
            }else
                f($v);
        }
    }
}

while(count($array) != count($array, 1))
{
    f($array);
}

print_r($array);

Note:

traverse array from outer to inner
traverse array from inner to outer

Monday, November 14, 2022
 
Only authorized users can answer the search term. Please sign in first, or register a free account.
Not the answer you're looking for? Browse other questions tagged :