Skip to content
Advertisement

PHP curl API request works. Using explode to make array, not giving key value pairs desired

Like the title says I am getting the API response just fine. I’ve cleaned the response data up several different ways. When attempting to use explode, I cannot get it to assign the string as the key and value pairs needed. I’ll post some of the data below. If I need to delimit the data differently for ease, I will. Tried dozens of examples over the last fourteen hours. Please help!

# Find the part of the string after the description
$mysearchstring = 'color';

# Minus one keeps the quote mark in front of color
$position = (stripos($response, $mysearchstring)-1);

    
#This selects the text after the description to the end of the file
$after_descrip = substr($response, $position);

echo "</br>__________Show the data after the description________________</br>";
echo $after_descrip;


echo "</br>__________Show the cleaned data________________</br>";
$cleaned = $after_descrip;
$cleaned1 = str_replace('{', "", $cleaned);
$cleaned2 = str_replace('}', "", $cleaned1);
$cleaned3 = str_replace('[', "", $cleaned2);
$cleaned4 = str_replace(']', "", $cleaned3);
$cleaned5 = str_replace('https://', "", $cleaned4);
$cleaned6 = str_replace('"', "", $cleaned5);

echo $cleaned6;

    
echo "</br>__________Explode is next________________</br>";

#Turn the string into an array but not the array I want 
$last_half = explode(':', $cleaned6);
print_r($last_half);

}

The cleaned data looks like this:

color:#3C3C3D,iconType:vector,iconUrl:cdn.coinranking.com/rk4RKHOuW/eth.svg,websiteUrl:www.ethereum.org,socials:name:ethereum,url:twitter.com/ethereum,type:twitter,name:ethereum,url:www.reddit.com/r/ethereum/

The resulting array looks like this:

Array ( [0] => color [1] => #3C3C3D,iconType [2] => vector,iconUrl [3] => cdn.coinranking.com/rk4RKHOuW/eth.svg,websiteUrl [4] => www.ethereum.org,socials [5] => name [6] => ethereum,url [7] => twitter.com/ethereum,type [8] => twitter,name [9] => ethereum,url [10] => www.reddit.com/r/ethereum/,type [11] => reddit,name [12] => ethtrader,url [13] =>

Color should be the first key, #3C3C3D should be the first value. The rest of the data should follow that format.

What do you think is the best way to go? Thank you.

-Rusty

Advertisement

Answer

Just one more step…

$last_half = explode(',', $cleaned6);
foreach($last_half as $item){
    list($k, $v) = explode(':', $item);
    $result[$k] = $v;    
}
print_r($result);
User contributions licensed under: CC BY-SA
10 People found this is helpful
Advertisement