PHP: Arrays Arrays Arrays – Map multiple values inside an array or an array in an array.

PHP: Arrays Arrays Arrays – Map multiple values inside an array or an array in an array.

Sometimes it can be necessary to store within an array not only single values but several values as array. At this point I would like to help you with a syntax example:

$values = ['A' => '1', 'B' => '2', 'C' => '3', 'D' => '4', 'E' => '5', 'F' => '6', 'G_MultipleValuesInArray' => array("7", "8", "9")];

Otherwise, just note that in the above example, the array is simply stored in a variable, making it easier to pass later.

Post to Array in Curl-Array

How do you get your form data into an array in an array for curl? Sounds confusing? Yes, a bit, so you can see in the code below under “CURLOPT_POSTFIELDS” an example of a json encoded array in array for curl.

if (isset($_POST["text"])) {
$text = $_POST["text"];
}

$curl = curl_init();

curl_setopt_array($curl, [
	CURLOPT_URL => "https://example.com/api",
	CURLOPT_RETURNTRANSFER => true,
	CURLOPT_FOLLOWLOCATION => true,
	CURLOPT_ENCODING => "",
	CURLOPT_MAXREDIRS => 10,
	CURLOPT_TIMEOUT => 30,
	CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
	CURLOPT_CUSTOMREQUEST => "POST",
	CURLOPT_POSTFIELDS => json_encode(['language' => "de", 'strength' => 3, 'text' => $text]),
	CURLOPT_HTTPHEADER => [
		"content-type: application/json",
		"x-api-host: example.com",
		"x-api-key: apikey"
	],
]);

Display array response

Normally there is also a corresponding response in JSON format, which to our surprise ends up as an array again. The above code is therefore extended a bit in our example and the response is stored as $response. After we have executed json_decode for the response we get an array again. We can output the values of this array again according to the example below (ArrayOutput1, ArrayOutput2, etc.).

$response = curl_exec($curl);
$err = curl_error($curl);

curl_close($curl);

if ($err) {
	echo "cURL Error #:" . $err;
} else {

$obj = $response;
$arr = json_decode($obj);

echo '</br></br>';
print $arr->{'ArrayOutput1'};
	
echo '</br></br>';
print $arr->{'ArrayOutput2'};
	
echo '</br></br>';
print $arr->{'ArrayOutput3'};
	
}

Headache from arrays, APIs and PHP? No problem – I’m happy to help you at reasonable hourly rates. You can reach me easily via my contact form.

Leave a Reply

Your email address will not be published.