Link to home
Start Free TrialLog in
Avatar of ScotTFO
ScotTFOFlag for United States of America

asked on

PHP array keys

I am querying an API and it sends a JSON response which I am then decoding into an array.  This part works fine, but the API sends the information in a rather unfriendly format.

I will paste the part I am having issues with.  Essentially I am trying to change each like keys into their own array.
Array
(
    [name] => Name
    [address] => 123 Street Rd
    [products[0][product_id]] => 1
    [products[0][price]] => 12.00
    [products[0][name]] => Product Name
    [products[0][product_qty]] => 1
    [products[1][product_id]] => 2
    [products[1][price]] => 3.00
    [products[1][name]] => Product Name
    [products[1][product_qty]] => 1
    [systemNotes[0]] => Note 1
    [systemNotes[1]] => Note 2
)
[

Open in new window

Now what I would like to do is to make
it like this:

Array
(
    [name] => Name
    [address] => 123 Street Rd
	[product] => Array
	(
		[0] => Array
		(
			[product_id] => 1
			[price] => 12.00
			[name] => Product Name
			[product_qty] => 1
		)
		[1] => Array
		(
			[product_id] => 2
			[price] => 3.00
			[name] => Product Name
			[product_qty] => 1
		)
    [systemNotes] => Array
	(
		[0] => Note 1
		[1] => Note 2
	)
)
[

Open in new window

Is there any practical way of doing this?

Thanks!
Avatar of Dave Baldwin
Dave Baldwin
Flag of United States of America image

Those look like the same thing in a different display to me.  What is the actual problem?
I agree wid DaveBaldwin, you may not understanding the way the "array" And "SUB-arrays" are shown as relationshilps as child-parent arrays, , to me this -
[products[0][product_id]] => 1
    [products[0][price]] => 12.00
    [products[0][name]] => Product Name
    [products[0][product_qty]] => 1

is the same as your desired -
[product] => Array
      (
            [0] => Array
            (
                  [product_id] => 1
                  [price] => 12.00
                  [name] => Product Name
                  [product_qty] => 1
            )

you show the "Code work" version to get that array,and in seems to be the same as the analysis print out for the same thing.

in your jason decode array output try this
if ($jArray['product'][0]['product_id'] == 1) echo "First Product element for product_id is ONE";
and see if  the array is as you want it.
Avatar of ScotTFO

ASKER

The top the key name is: [products[0][product_id]] and is not a multidimensional array.
OK, looks like I'm the one not understanding this?
to be certain , since I do not have this to test, you access it like
if ($jArray["products[0][product_id]"] == 1) echo "First Product is equal ONE";

if that's the case then you will likely need to loop through the whole json array and then build a new second separate array, by separating out the "product" and [systemNotes[1]] keys and then creating sub arrays in the new array and adding the values from the old array. You may could use the [ ] in the key name for a separator, but if there are more than a couple of Keys other than product and systemNotes it could take some time to get it all correct.
Hello ScotTFO,

If you can give your json part, it will help more to give you some proper solution.

Thank you.

Amar Bardoliwala.
+1 for what @amar_bardoliwala asks.  This is a data-dependent problem, and the easiest way to get help is for you to post the test data so we can replicate the issue and give you tested-and-working solutions.

http://sscce.org/

Standing by, ~Ray
OK, I remembered some string parse I did years ago to chop out user format in a bulletin board post using the [   as they use here in this EE post thing. Amazingly I found that code, and sloped together this, which to me does what you require, All I had to work wid was your JSON Array definition, which may be a shortened exert of the JSON thing?

This works for me on my server -
$jArray = array('name' => 'Name1', 'address' => '123 Street Rd', 'products[0][product_id]' => 11, 
    'products[0][price]' => 12.01, 'products[0][name]' => 'Product Name1', 'products[0][product_qty]' => 1, 
    'products[1][product_id]' => 22, 'products[1][price]' => 3.00, 'products[1][name]' => 'Product Name2', 'products[1][product_qty]' => 2,
    'systemNotes[0]' => 'Note 1', 'systemNotes[1]' => 'Note 2');
$modArray = array();
$newA = '';
$aNum = 0;
foreach ( $jArray as $key => $value ) {
$pos1 = strpos($key, '[');
    if (($pos1 === false) || ($pos1 < 2)) $modArray[$key] = $value;
      else {$pos2 = strpos($key, ']');
       if ($pos2 > $pos1) {
       $sb = substr($key, 0, $pos1);
      ++$pos1;
      if ($sb != $newA) {
        $newA = $sb;
        $sb = substr($key, $pos2+2,-1);
        $aNum = (int) substr($key, $pos1, $pos2-$pos1);
        if ($sb) $modArray[$newA][$aNum][$sb] = $value;
          else $modArray[$newA][$aNum] = $value;
       } else {
        $ne = substr($key, $pos2+2,-1);
        $sb = (int) substr($key, $pos1, $pos2-$pos1);
        if ($sb == $aNum) {
          $modArray[$newA][$aNum][$ne] = $value;
          } else {
          $aNum=$sb;
          if ($ne) $modArray[$newA][$aNum][$ne] = $value;
          else $modArray[$newA][$aNum] = $value;
           }
       }
     } else $modArray[$key] = $value;
  }
}

echo '<pre>';
print_r($jArray);
echo "\n= = = = = = = = = = =\n";
print_r($modArray);
echo '</pre>';

Open in new window

But this is a short on time effort for me, It is made specifically and only for the  KEY Strings of type format shown in your example, the first part of key -
products[0][product_id]
systemNotes[1]
as products and  systemNotes can be ANY string at least 2 characters long
the ARRAY brackets as  [2] MUST have only numbers, this will FAIL if there are non-number strings for the 2 part
any string characters past the first ] MUST be in brackets as  [product_qty], the brackets are removed and the string as "product_qty" is used as a KEY in a new sub array.
This is not so easy to do if the return JSON are not of a consistent KEY format and arrangement.
Ask questions if you need more info. I hope you are still responding here, post if you can.
ASKER CERTIFIED SOLUTION
Avatar of Ray Paseur
Ray Paseur
Flag of United States of America image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
@ScotTFO: Any progress on getting us that JSON string?  Thanks, ~Ray
The answer at https:#a39339897 produces this, which is exactly what the author asked for.
Array
(
    [name] => Name1
    [address] => 123 Street Rd
    [products[0][product_id]] => 11
    [products[0][price]] => 12.01
    [products[0][name]] => Product Name1
    [products[0][product_qty]] => 1
    [products[1][product_id]] => 22
    [products[1][price]] => 3
    [products[1][name]] => Product Name2
    [products[1][product_qty]] => 2
    [systemNotes[0]] => Note 1
    [systemNotes[1]] => Note 2
)

Array
(
    [name] => Name1
    [address] => 123 Street Rd
    [products] => Array
        (
            [0] => Array
                (
                    [product_id] => 11
                    [price] => 12.01
                    [name] => Product Name1
                    [product_qty] => 1
                )

            [1] => Array
                (
                    [product_id] => 22
                    [price] => 3
                    [name] => Product Name2
                    [product_qty] => 2
                )

        )

    [systemNotes] => Array
        (
            [0] => Note 1
            [1] => Note 2
        )

)

Open in new window